본문 바로가기
데이터분석/python

Pandas API

by 직장인B 2021. 8. 18.

python 3

pandas 1.1.5

numpy 1.19.5

 

- pandas는 파이썬 라이브러리로, DataFrame 이라는 자료 객체를 이용한 여러가지 데이터 처리 및 분석 API를 제공한다. 

 


# DataFrame 생성

 

1 . Numpy Array -> DataFrame

import numpy as np
import pandas as pd

lis = [ [1,2,3], [4,5,6], [7,8,9] ]
arr = np.array(lis) # 2 차원 array

df = pd.DataFrame(arr) # lis를 넣어도 동일한 결과를 얻음

// df
	0	1	2
0	1	2	3
1	4	5	6
2	7	8	9

- column / index 추가

import numpy as np
import pandas as pd

lis = [ [1,2,3], [4,5,6], [7,8,9] ]
arr = np.array(lis) # 2 차원 array

columns = ['col1', 'col2', 'col3']
index = ['i1', 'i2', 'i3']

df = pd.DataFrame(arr, columns = columns, index= index) # lis를 넣어도 동일한 결과를 얻음

// df
	col1	col2	col3
i1	1	2	3
i2	4	5	6
i3	7	8	9

 

2 . Dict -> DataFrame

import pandas as pd

dic = { 'col1':[1,2,3], 'col2':[4,5,6], 'col3':[7,8,9] }

df = pd.DataFrame(dic)

df
//
	col1	col2	col3
0	1	4	7
1	2	5	8
2	3	6	9

 

3 . CSV file -> DataFrame

import pandas as pd

path = 'path/to/file.csv'

df = pd.read_csv(path, header=True, index=False)

// df
	0	1	2
0	1	2	3
1	4	5	6
2	7	8	9

 

# DataFrame 기본 조작

 

// df

  col1 col2 col3
0 1 4 7
1 2 5 8
2 3 6 9

// ddf

  col1 col2 col3
i1 1 4 7
i2 2 5 8
i3 3 6 9

 

## 기본 API

 

- DataFrame 복사

df_c = df.copy()

// df_c
	col1	col2	col3
0	1	4	7
1	2	5	8
2	3	6	9

- DataFrame size 확인

// df.shape
(3, 3)

 

## Column 관련

 

- Column 출력

cols = df.columns

// cols
Index(['col1', 'col2', 'col3'], dtype='object')

- Column 변경

df_1 = df.copy()
df_2 = df.copy()

# 전체 Column 변경
df_1.columns = ['x','y','z']

// df_1
	x	y	z
0	1	4	7
1	2	5	8
2	3	6	9

# 지정 Column 변경
replace_info_dic = {'col1':'x'}
df_2 = df_2.rename(columns = replace_info_dic, inplace = False)

// df_2
	x	col2	col3
0	1	4	7
1	2	5	8
2	3	6	9

- Column 순서 변경

reorder_cols = ['col3', 'col2', 'col1']

# 추출 
df_1 = df[reorder_cols]

# 인덱싱
df_2 = df.reindex(colums=reorder_cols)

// df_1, df_2
	col3	col2	col1
0	7	4	1
1	8	5	2
2	9	6	3

- Column 삭제 

df_1 = df[['col1', 'col3']]
df_2 = df.drop(['col2'], axis=1)

// df_1, df_2
	col1	col3
0	1	7
1	2	8
2	3	9

 

 

## Index 관련

 

- Index 출력

index = df.index

// index
RangeIndex(start=0, stop=3, step=1)

- Index 변경 및 설정

df_1 = df.copy()
df_1.index = ['a','b','c']
df_2 = df.set_index('col1')

// df_1
	col1	col2	col3
a	1	4	7
b	2	5	8
c	3	6	9

// df_2
	col2	col3
col1		
1	4	7
2	5	8
3	6	9

- Index 삭제

df_c = df.drop([1], axis=0)

// df_c
	col1	col2	col3
0	1	4	7
2	3	6	9

 

 

## 데이터 추출

 

- Column 추출

col2_1 = df['col2']
col2_2 = df.loc[:,'col2']
col2_3 = df.loc[:,['col2']]
col2_4 = df.iloc[:,1]

// col2_1, col2_2, col2_4 - Series
0    4
1    5
2    6
Name: col2, dtype: int64

// col2_3 - DataFrame
   col2
0     4
1     5
2     6

- Row 추출

row1_1 = df[1:2]
row1_2 = df.loc[1]
row1_3 = df.loc[1:1]
row1_4 = df.iloc[1]
row1_5 = df.iloc[1:2]

// row1_1, row1_3, row1_5 - DataFrame
	col1	col2	col3
1	2	5	8

// row1_2, row1_4 - Series
col1    2
col2    5
col3    8
Name: 1, dtype: int64

- Element 추출

elm_1xcol2_1 = df[1:2]['col2']
elm_1xcol2_2 = df.loc[1,'col2']
elm_1xcol2_3 = df.loc[1:1,['col2']]
elm_1xcol2_4 = df.iloc[1,1]
elm_1xcol2_5 = df.iloc[1:2,1:2]

// elm_1xcol2_1 - Series
1    5
Name: col2, dtype: int64

// elm_1xcol2_2, elm_1xcol2_4 - int
5

// elm_1xcol2_3, elm_1xcol2_5 - DataFrame
	col2
1	5

 

## 데이터 변경

 

- 위치 지정 변경

ddf1 = ddf.copy()
ddf2 = ddf.copy()

ddf1.loc['i2', 'col2'] = 'x'
ddf2.iloc[1,1] = 'x'

// ddf1, ddf2
	col1	col2	col3
i1	1	4	7
i2	2	x	8
i3	3	6	9

- apply 함수 이용

ddf1 = ddf.copy()
ddf2 = ddf.copy()

ddf1['col2'] = ddf1['col2'].apply(lambda x: x + 10)

// ddf1
	col1	col2	col3
i1	1	14	7
i2	2	15	8
i3	3	16	9

ddf2 = ddf2.apply(lambda x: x + 10)

// ddf2
	col1	col2	col3
i1	11	14	17
i2	12	15	18
i3	13	16	19

 

 

## 데이터 붙이기

 

- Column 추가

df1 = df.copy()
df2 = df.copy()
df3 = df.copy()

new_col = ['x', 'x', 'x']

df1['new'] = new_col

// df1
	col1	col2	col3	new
0	1	4	7	x
1	2	5	8	x
2	3	6	9	x

df2.insert(1, 'new', new_col, True)

// df2
	col1	new	col2	col3
0	1	x	4	7
1	2	x	5	8
2	3	x	6	9

new_col_dic = { 'x':7, 'y':8, 'z':9 }

df3['new'] = new_col_dic

// df3
	col1	col2	col3	new
0	1	4	7	x
1	2	5	8	y
2	3	6	9	z

 

- DataFrame Join

-- Concat API 사용 : 인덱스 기준 join

dic = { 'j1': ['x','x'], 'j2': ['y','y'] }
ddf1 = pd.DataFrame(dic, index=['i2','i3'])

// ddf1
	j1	j2
i2	x	y
i3	x	y

ddf_j1 = pd.concat([ddf, ddf1], axis=1, join='outer') 

// ddf_j1
	col1	col2	col3	j1	j2
i1	1	4	7	NaN	NaN
i2	2	5	8	x	y
i3	3	6	9	x	y

ddf_j2 = pd.concat([ddf, ddf1], axis=1, join='inner')

// ddf_j2
	col1	col2	col3	j1	j2
i2	2	5	8	x	y
i3	3	6	9	x	y

ddf_j3 = pd.concat([ddf1, ddf], axis=1)

// ddf_j3
	j1	j2	col1	col2	col3
i2	x	y	2	5	8
i3	x	y	3	6	9
i1	NaN	NaN	1	4	7

-- Merge API 사용 : 공통 컬럼 기준 join

dic = { 'col2':[5,6], 'j1': ['x','x'], 'j2': ['y','y'] }
df1 = pd.DataFrame(dic)

// df1
	col2	j1	j2
0	5	x	y
1	6	x	y

df_j1 = pd.merge(df, df1, on='col2', how='inner')

// df_j1
	col1	col2	col3	j1	j2
0	2	5	8	x	y
1	3	6	9	x	y

df_j2 = pd.merge(df, df1, on='col2', how='outer')

// df_j2
	col1	col2	col3	j1	j2
0	1	4	7	NaN	NaN
1	2	5	8	x	y
2	3	6	9	x	y

- DataFrame add

dic = { 'col1': ['x','x'], 'col2': ['y','y'] }
df1 = pd.DataFrame(dic)

// df1
	col1	col2
0	x	y
1	x	y

df_a1 = pd.concat([df, df1], axis=0, join='outer')

// df_a1
	col1	col2	col3
0	1	4	7.0
1	2	5	8.0
2	3	6	9.0
0	x	y	NaN
1	x	y	NaN

df_a2 = pd.concat([df, df1], axis=0, join='inner')

// df_a2
	col1	col2
0	1	4
1	2	5
2	3	6
0	x	y
1	x	y

 

 

## 데이터 전처리

 

- 결측치 제거

df_n = df.copy()
df_n.iloc[1,1] = None

// df_n
	col1	col2	col3
0	1	4.0	7
1	2	NaN	8
2	3	6.0	9

df_n1 = df_n.dropna(axis=0)

// df_n1
	col1	col2	col3
0	1	4.0	7
2	3	6.0	9

df_n2 = df_n.dropna(axis=1)

// df_n2
	col1	col3
0	1	7
1	2	8
2	3	9

- 결측치 대체

df_n = df.copy()
df_n.iloc[1,0] = None
df_n.iloc[1,1] = None
df_n.iloc[1,2] = None

// df_n
	col1	col2	col3
0	1.0	4.0	7.0
1	NaN	NaN	NaN
2	3.0	6.0	9.0

df_n1 = df_n.fillna(0)

// df_n1
	col1	col2	col3
0	1.0	4.0	7.0
1	0	0	0
2	3.0	6.0	9.0

fill_values = {'col1':'x', 'col2': 'y', 'col3':'z' }
df_n2 = df_n.fillna(value=fill_values)

// df_n2
	col1	col2	col3
0	1	4	7
1	x	y	z
2	3	6	9

df_n3 = df_n.fillna(method = 'bfill')

// df_n3
	col1	col2	col3
0	1.0	4.0	7.0
1	3.0	6.0	9.0
2	3.0	6.0	9.0

df_n4 = df_n.fillna(method = 'ffill')

// df_n4
	col1	col2	col3
0	1.0	4.0	7.0
1	1.0	4.0	7.0
2	3.0	6.0	9.0

- 데이터 타입 변경

df1 = df.copy()

df1['col2'] = df1['col2'].astype('float')

// df1
	col1	col2	col3
0	1	4.0	7
1	2	5.0	8
2	3	6.0	9

 

## 데이터 분석

 

- 결측치 확인

df_n = df.copy()
df_n.iloc[1,1] = None

// df_n
	col1	col2	col3
0	1	4.0	7
1	2	NaN	8
2	3	6.0	9

// df_n.isnull()
	col1	col2	col3
0	False	False	False
1	False	True	False
2	False	False	False

- DataFrame 정보 요약

// ddf.info()
Index: 3 entries, i1 to i3
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   col1    3 non-null      int64
 1   col2    3 non-null      int64
 2   col3    3 non-null      int64
dtypes: int64(3)
memory usage: 96.0+ bytes

 - DataFrame 기술 통계량 테이블

// df.describe()
	col1	col2	col3
count	3.0	3.0	3.0
mean	2.0	5.0	8.0
std	1.0	1.0	1.0
min	1.0	4.0	7.0
25%	1.5	4.5	7.5
50%	2.0	5.0	8.0
75%	2.5	5.5	8.5
max	3.0	6.0	9.0

# apply 함수 직접 적용
// df.apply(lambda x: max(x))
col1     6
col2    15
col3    24
dtype: int64

 

 

## 데이터 시각화

 

- line plot

// df.plot(x='col1', y='col2', kind='line')

- box plot

// df.plot(y='col2', kind='box')

'데이터분석 > python' 카테고리의 다른 글

딥러닝 코드 모음  (0) 2021.08.20