꺼내먹는지식 준
Pandas 본문
Numpy 와 통합되어 강력한 기능 제공
인덱싱, 연산 함수, 전처리 함수 제공
데이터 처리 및 통계 분석
전체 표: Data table, Sample
Columns 는 atrribute, field, feature 이라고도 부른다.
Row 한 줄을 instance, tuple, row 라고 부른다.
Data 를 value 라고 부르기도 한다.
1.데이터 읽어 들이는 법
df_data = pd.read_csv( 저장주소 , sep= "\s+", header = None)
랜덤으로 생성되는 csv 파일을 하나 줏어왔다.
*"\s+" 읽어들일 때 나누는 기준을 single space 즉 띄어쓰기로 하는데(s), 각 데이터 한 줄 마다 single space 가 여러개 존재한다는 뜻(+)
df_data.head(n)
데이터의 최상단 n 개 만큼 보여주어라.
첫 줄 column도 데이터 처리 되었다.
df_data.columns = ["hajun", "Jack", "Elijah", "Max", "Eun", "Hue", "Kale"... ]
등등 데이터의 column names를 설정해줄 수 있다.
df_data.values() 로 모든 value 의 값들을 볼 수 있다.
DataFrame: Data Table 전체를 포함하는 Object
Series: DtaFrame 중 하나의 Column에 해당하는 데이터의 모음 Object
필요에 따라서,
list_data = [1,2,3,4,5]
example = Series(data = list_data)
0 1
1 2
2 3
3 4
4 5
index 는 자동 생성, index 값 바꿔주는 것 가능.
example = Series(data = list_data, index = 인덱스 이름)
dict_data = {'a': 1, 'b': 1, 'c': 1}
example = Series(dict_data, name= "example_data")
dict type 은 자동으로 key 값이 index, value 값이 item 으로 설정된다.
a 1
b 1
c 1
Name: example_data
example.index로
--> Index(['a','b','c','d','e'], dtype = 'object')
df_data.index
따로 index 를 설정해 주지 않아서 다음과 같이 결과가 나왔다.
df_data 의 column 값과 index 값을 바꿔보자.
다음과 같이 index 와 column가 변한걸로 볼 수 있다.
2. Indexing Slicing
df_data[5]: column의 접근 방법
*접근 방법은 두가지 방식, 기능은 동일: df_data.5 혹은 df_data[5] 단, column name 을 integer 로 했더니 df_data.5 는 작동하지 않는다.
Series 형 데이터면 해당 접근이 index 접근이지만, dataFrame에서는 column 접근
그리고 각 column 을 series data라고 한다.
df_data[5][2]: column name 5, index name 2 번의 데이터(value) 반환
*여기서 유의할 점은 column과 index 의 number 가 아니고, colum과 index의 name 으로 indexing 한다.
*.astype(int) 타입 바꾸는 함수
df_data.values 값 리스트만
df_data.index index 리스트만
Data에 대한 정보를 저장
dataFrame의 메모리 구조는 index 와 column을 모두 알아야만 하고, 각 column의 data type 이 다를 수 있다. (float, in ... 등등)
주로 csv, excel 데이터를 많이 불러 사용한다.
loc - index location
iloc - index position
df.loc[10]
5 380086
6 Mrs.
7 Carol
8 V
9 Murphy
10 F
11 carol.murphy@gmail.com
12 Eugene Murphy
13 Katherine Murphy
14 Peterson
15 6/30/1958
16 10:39:33 AM
17 59.12
18 40
19 1/28/1983
20 Q1
21 H1
22 1983
23 1
24 January
25 Jan
26 28
27 Friday
28 Fri
29 34.52
30 60918
31 20%
32 423-67-7023
33 216-336-0009
34 Blanchester
35 Clinton
36 Blanchester
37 OH
38 45107
39 Midwest
40 cvmurphy
41 Uc+VG%vuZU<k
'10' 에 해당되는 index 의 column name 과 value 가 return 되었다.
df.loc[:10]
즉 index 이름이 10에 도달할때까지의 모든 index 에 해당하는 column name 과 value 를 반환하다.
5 6 7 ... 39 40 41
2 Emp ID Name Prefix First Name ... Region User Name Password
3 677509 Drs. Lois ... West lhwalker DCa}.T}X:v?NP
4 940761 Ms. Brenda ... South bsrobinson TCo\j#Zg;SQ~o
5 428945 Dr. Joe ... Midwest jwrobinson GO4$J8MiEh[A
6 408351 Drs. Diane ... Northeast dievans 0gGRtp1HfL<r5
7 193819 Mr. Benjamin ... Midwest brrussell Rd<Y8cp!@R;*%F
8 499687 Mr. Patrick ... Midwest pfbailey K7&5aY/*
9 539712 Ms. Nancy ... South ntbaker xJdKlAcYQhT_BE#
10 380086 Mrs. Carol ... Midwest cvmurphy Uc+VG%vuZU<k
이러한 형태가 반환된다.
df.loc[10]과 동일한 값을 df.iloc[] 으로 출력하기 위해서 index name 10의 index number을 확인해보면 8이다.
df.iloc[8]
5 380086
6 Mrs.
7 Carol
8 V
9 Murphy
10 F
11 carol.murphy@gmail.com
12 Eugene Murphy
13 Katherine Murphy
14 Peterson
15 6/30/1958
16 10:39:33 AM
17 59.12
18 40
19 1/28/1983
20 Q1
21 H1
22 1983
23 1
24 January
25 Jan
26 28
27 Friday
28 Fri
29 34.52
30 60918
31 20%
32 423-67-7023
33 216-336-0009
34 Blanchester
35 Clinton
36 Blanchester
37 OH
38 45107
39 Midwest
40 cvmurphy
41 Uc+VG%vuZU<k
df.loc[:10]은 index name 10 까지의 데이터 출력,
df.iloc[:10]은
5 6 7 ... 39 40 41
2 Emp ID Name Prefix First Name ... Region User Name Password
3 677509 Drs. Lois ... West lhwalker DCa}.T}X:v?NP
4 940761 Ms. Brenda ... South bsrobinson TCo\j#Zg;SQ~o
5 428945 Dr. Joe ... Midwest jwrobinson GO4$J8MiEh[A
6 408351 Drs. Diane ... Northeast dievans 0gGRtp1HfL<r5
7 193819 Mr. Benjamin ... Midwest brrussell Rd<Y8cp!@R;*%F
8 499687 Mr. Patrick ... Midwest pfbailey K7&5aY/*
9 539712 Ms. Nancy ... South ntbaker xJdKlAcYQhT_BE#
10 380086 Mrs. Carol ... Midwest cvmurphy Uc+VG%vuZU<k
11 477616 Hon. Frances ... South fbyoung K}^USc0l7[A
df_data[5][2]: Emp ID (df_data[5,2])
그냥 indexing 할 때는 column name, index name 순으로 접근하지만
df_data.loc[5,5]: 는 index name, column name 순으로 접근한다.
df_data.loc[2, 5]: Emp ID (df_data.loc[2][5])
df_data.loc[:, 5]: 모든 index 에 대하여, 5번 column
2 Emp ID
3 677509
4 940761
5 428945
6 408351
...
98 639892
99 704709
100 461593
101 392491
102 495141
df_data[5][3:] > 500000 비교를 통해
boolean data 를 얻을 수 있지만, 문제는 현재 내가 사용하는 데이터에 str 이 포함되어 있어서 어렵다.
----------------------------------------------------------------------------------------
그러면 str 이 포함된 첫 줄을, 아예 column name 으로 지정해주자.
----------------------------------------------------------------------------------------
0 Emp ID Name Prefix First Name Middle Initial Last Name ... State Zip Region User Name Password
1 677509 Drs. Lois H Walker ... CO 80224 West lhwalker DCa}.T}X:v?NP
2 940761 Ms. Brenda S Robinson ... LA 71078 South bsrobinson TCo\j#Zg;SQ~o
3 428945 Dr. Joe W Robinson ... IN 46057 Midwest jwrobinson GO4$J8MiEh[A
4 408351 Drs. Diane I Evans ... PA 16328 Northeast dievans 0gGRtp1HfL<r5
깔끔하게 정리되었다. 단, index 숫자는 하나씩 밀렸다.
1 80224
2 71078
3 46057
4 16328
5 54940
...
96 39532
97 60351
98 48278
99 99627
100 48801
Name: Zip, Length: 100, dtype: object
dtype이 object이다. dtype 을 바꿔보자.
df_data.Zip = df_data.Zip.astype(float) *여기서 유의해야 할 점은 바로, astype선언한 것을 입력해줘야 설정이 완료된다는 것이다.
1 True
2 True
3 False
4 False
5 True
...
96 False
97 True
98 False
99 True
100 False
Name: Zip, Length: 100, dtype: bool
드디어 데이터와 integer 비교가 가능해졌다. 새로운 데이터가 생성되었다.
0 Emp ID Name Prefix First Name Middle Initial Last Name Gender E Mail ... City State Zip Region User Name Password Bool
1 677509 Drs. Lois H Walker F lois.walker@hotmail.com ... Denver CO 80224.0 West lhwalker DCa}.T}X:v?NP True
2 940761 Ms. Brenda S Robinson F brenda.robinson@gmail.com ... Stonewall LA 71078.0 South bsrobinson TCo\j#Zg;SQ~o True
3 428945 Dr. Joe W Robinson M joe.robinson@gmail.com ... Michigantown IN 46057.0 Midwest jwrobinson GO4$J8MiEh[A False
4 408351 Drs. Diane I Evans F diane.evans@yahoo.com ... Hydetown PA 16328.0 Northeast dievans 0gGRtp1HfL<r5 False
크기가 너무 커서 좀 깨지지만, column이 잘 추가된 것을 볼 수 있다.
to_csv, .T (transpose) 등 여러 기능이 제공된다.
column 삭제는
del df_data["Bool"] 로 가능하다.
df_data.drop("Bool", axis = 1)
pandas 에서 axis = 0은 index, axis = 1은 column 을 말한다.
json file이
pop = {"Hajun" : {1995: 1, 2022: 28}, "You": {1997: 1, 2022: 26}}
이런 형태로 넘어오면 pandas로 dataframe을 만들 수 있다는 것만 알아두자.
'Python > 간단한 이해 글' 카테고리의 다른 글
Python Zip (0) | 2022.02.04 |
---|---|
numpy (0) | 2022.01.18 |
String 및 변수, 함수 관련 (0) | 2022.01.17 |
Python List (0) | 2022.01.17 |
컴퓨터 기본 내용 정리, 파이썬 기본 내용 정리 (0) | 2022.01.17 |