파이썬 라이브러리를 활용한 데이터 분석 - 데이터 정제 및 준비

esc247·2022년 6월 14일
0

Data Analysis

목록 보기
3/10
post-thumbnail

누락된 데이터 처리하기

  • 산술 데이터에 한해 pandas는 누락된 데이터 NaN으로 취급
import pandas as pd
import numpy as np
string_data = pd.Series(['aardvark','artichoke',np.nan,'avocado'])

string_data.isnull()
***
0    False
1    False
2     True
3    False
dtype: bool
  • 파이썬의 내장 None 값 또한 NA
  • dropna
    누락된 데이터가 있는 축을 제외
  • fillna
    누락된 데이터를 대신할 값을 채우거나 'ffill', 'bfill'같은 보간 메서드를 적용
  • isnull
    누락되거나 NA인 값을 알려주는 bool 값이 저장된 같은 형의 객체 반환
  • notnull
    isnull과 반대

누락된 데이터 골라내기

  • Series의 경우
from numpy import nan as NA
data =pd.Series([1,NA,3.5,NA,7])
data.dropna() # data[data.notnull()]
***
0    1.0
2    3.5
4    7.0
dtype: float64
  • DataFrame
data = pd.DataFrame([[1.,6.5,3],[1.,NA,NA],
                     [NA,NA,NA], [NA,6.5,3.]])
cleaned = data.dropna()
cleaned
***
	0	1	2
0	1.0	6.5	3.0
  • how = 'all' ->모두 NA 값인 로우만 제외
  • axis = 1 -> 컬럼을 제외
  • 몇 개 이상의 값이 들어 있는 로우만 살펴보고 싶으면 thresh 인자에 원하는 값 넘기면 됨.

결측치 채우기

  • fillna 에 채워 넣고 싶은 값 넘겨주면 됨.
  • 사전값 넘겨서 컬럼마다 다른 값 채울 수 있음.
df.fillna({1:0.5,2:0})
***
		0			1			2
0	0.335656	0.500000	0.000000
1	0.398244	0.500000	0.000000
2	0.325841	0.500000	-1.021482
3	0.203460	0.500000	0.722391
4	-1.280867	-0.482576	0.912558
5	-1.092729	-0.442173	-0.314900
6	-1.531893	1.415888	-0.136006
  • inplace = True : 기존 객체 변경
  • 보간 메서드 사용 가능
df= pd.DataFrame(np.random.randn(6,3))
df.iloc[2:,1] = NA
df.iloc[4:,2] = NA
df.fillna(method='ffill', limit=2)
***
		0			1			2
0	0.764332	1.033776	1.330905
1	1.003583	0.136773	0.143033
2	0.091921	0.136773	1.147770
3	-1.223208	0.136773	1.112935
4	-1.198974	NaN			1.112935
5	0.146298	NaN			1.112935

데이터 변형

중복 제거

  • .duplicated() : 각 로우가 중복인지 알려주는 bool Series 반환
  • .drop_duplicates() : duplicated 배열이 false인 (중복이 아닌 값들) DataFrame 반환
  • keep = 'last' : 기본적으로 처음 발견 값 유지인데, 이 옵션 넘기면 마지막으로 발견된 값 반환
  • Series의 .map() :

값 치환

  • .replace()
data = pd.Series([1.,-999.,2.,-999.,-1000.,3.])
data.replace(-999,np.nan)
data.replace([-999,-1000], np.nan) #여러 개 한 번에 치환
***
0    1.0
1    NaN
2    2.0
3    NaN
4    NaN
5    3.0
dtype: float64
* * *
data.replace([-999,-1000],[np.nan,0]) #
data.replace({-999: np.nan,-1000:0}) #같은 기능
***
0    1.0
1    NaN
2    2.0
3    NaN
4    0.0
5    3.0
dtype: float64

표시자/더미 변수 계산

  • 분류값을 더미나 표시자 행렬로 전환
    만약 DataFrame의 한 컬럼에 k가지 값이 있다면 k개의 컬럼이 있는 DataFrame이나 행렬을 만들고 값으로 1,0 채워 넣는다.
df = pd.DataFrame({'key' : ['b','b','a','c','a','b'],
                   'data1':range(6)})
pd.get_dummies(df['key'])
***
	a	b	c
0	0	1	0
1	0	1	0
2	1	0	0
3	0	0	1
4	1	0	0
5	0	1	0
  • prefix : 접두어 추가 후 다른 데이터와 병합 가능
dummies = pd.get_dummies(df['key'],prefix='key')
df_with_dummy = df[['data1']].join=(dummies)
df_with_dummy
***
	key_a	key_b	key_c
0	0		1		0
1	0		1		0
2	1		0		0
3	0		0		1
4	1		0		0
5	0		1		0
  • DataFrame 의 한 로우가 여러 카테고리에 속할 때 (ex. movielens)
#장르 목록 추출
all_genres = []
for x in movies.genres:
  all_genres.extend(x.split('|'))
genres = pd.unique(all_genres)
genres
***
array(['Animation', "Children's", 'Comedy', 'Adventure', 'Fantasy',
       'Romance', 'Drama', 'Action', 'Crime', 'Thriller', 'Horror',
       'Sci-Fi', 'Documentary', 'War', 'Musical', 'Mystery', 'Film-Noir',
       'Western'], dtype=object)
#0으로 초기화된 DataFrame 생성
zero_matrix = np.zeros((len(movies),len(genres)))
dummies = pd.DataFrame(zero_matrix, columns = genres)
#각 영화 순회, dummies의 각 로우 항목 1로 설정.
gen = movies.genres[0]
dummies.columns.get_indexer(gen.split('|'))
#iloc 이용해 색인에 맞게 값 대입
for i ,gen in enumerate(movies.genres):
  indcies = dummies.columns.get_indexer(gen.split('|'))
  dummies.iloc[i,indcies]=1
movies_windic = movies.join(dummies.add_prefix('Genre_'))
movies_windic.iloc[0]
***
movei_id                                       1
title                           Toy Story (1995)
genres               Animation|Children's|Comedy
Genre_Animation                              1.0
Genre_Children's                             1.0
Genre_Comedy                                 1.0
Genre_Adventure                              0.0
Genre_Fantasy                                0.0
Genre_Romance                                0.0
Genre_Drama                                  0.0
Genre_Action                                 0.0
Genre_Crime                                  0.0
Genre_Thriller                               0.0
Genre_Horror                                 0.0
Genre_Sci-Fi                                 0.0
Genre_Documentary                            0.0
Genre_War                                    0.0
Genre_Musical                                0.0
Genre_Mystery                                0.0
Genre_Film-Noir                              0.0
Genre_Western                                0.0
Name: 0, dtype: object
  • cut 같은 이산함수와 조합하면 유용
np.random.seed(12345)
values = np.random.rand(10)
bins = [0,0.2,0.4,0.6,0.8,1.]
pd.get_dummies(pd.cut(values,bins))
***
	(0.0, 0.2]	(0.2, 0.4]	(0.4, 0.6]	(0.6, 0.8]	(0.8, 1.0]
0		0	0	0	0	1
1		0	1	0	0	0
2		1	0	0	0	0
3		0	1	0	0	0
4		0	0	1	0	0
5		0	0	1	0	0
6		0	0	0	0	1
7		0	0	0	1	0
8		0	0	0	1	0
9		0	0	0	1	0

문자열 다루기

객체 메서드

  • .split('') : ''로 분리 ,
    .strip() : 공백 문자 제거
  • .join() : 문자열 합치기
val = 'a,b, guido'
pieces = [x.strip() for x in val.split(',')
***
['a', 'b', 'guido']
#더하기 연산 대신 join
','.join(pieces)
***
'a,b,guido'
  • .index(), .find() : 찾는 부분 인덱스 반환
    단 없을 경우 find 는 -1 반환, index는 예외 발생시킴
  • .count() : 특정 부분 문자열 몇 건 발견되었나
  • .replace( , ) : 찾아낸 패턴 다른 문자열로 치환
profile
막상 하면 모르니까 일단 하자.

0개의 댓글