NaN값 삭제하기
dropna를 사용하여 NaN값을 삭제한다.
df.dropna()
NaN값 0으로 채우기
fillna()를 사용하여 NaN값을 0으로 채운다.
df.fillna(0) # 0으로 채운다
NaN값 평균치로 채우기
fillna를 사용하여 평균치로 NaN값을 채운다.
먼저, 각 컬럼의 NaN값 개수를 확인한다.
컬럼의 평균값 확인하고 평균값으로 채운다.
df.fillna({'칼럼명':int(df['칼럼명'].mean)}, inplace=True)
# inplace=True 이 속성은 데이터 프레임 원본의 NaN값을 채운다는 의미이다.
NaN값의 개수를 다시 확인해보면 모두 0으로 잘 처리되었다.
NaN값 보간법으로 채우기
피쳐의 정보성을 강조하기 위해 보간법을 사용해 NaN값을 채울 수 있다. interplate를 사용하면 된다.
df.interpolate(inplace=True)
interpolate 메소드는 보간법을 사용하여 NaN 값을 채운다.
DataFrame.interpolate(method='linear', axis=0, limit=None, inplace=False, limit_direction=None, limit_area=None, downcast=None, **kwargs)
'method'는 사용하는 보간법의 종류로 default값은 linear이다.
- ‘linear’: 인덱스를 무시하고 등간격으로 값을 보간함.
>>> s = pd.Series([0, 1, np.nan, 3])
>>> s
0 0.0
1 1.0
2 NaN
3 3.0
dtype: float64
>>> s.interpolate() # 디폴트값 linear
0 0.0
1 1.0
2 2.0
3 3.0
dtype: float64
- ‘pad’: 기존값으로 값을 보간함.
>>> s = pd.Series([np.nan, "single_one", np.nan,
"fill_two_more", np.nan, np.nan, np.nan,
4.71, np.nan])
>>> s
0 NaN
1 single_one
2 NaN
3 fill_two_more
4 NaN
5 NaN
6 NaN
7 4.71
8 NaN
dtype: object
>>> s.interpolate(method='pad', limit=2) # 한 번에 최대 2개의 연속 결측치를 채운다.
0 NaN
1 single_one
2 single_one
3 fill_two_more
4 fill_two_more
5 fill_two_more
6 NaN
7 4.71
8 4.71
dtype: object
등이 있다.
참고자료
pandas.DataFrame.interpolate — pandas 1.4.1 documentation
‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, ‘spline’, ‘barycentric’, ‘polynomial’: Passed to scipy.interpolate.interp1d. These methods use the numerical values of the index. Both ‘polynomial’ and ‘spline’ req
pandas.pydata.org
Lv2 전처리 2/2 python 파이썬 결측치 대체 보간법
#오늘의 파이썬 #1일1오파 #파이썬 # python
dacon.io
댓글