pandas.fillna() 누락 된 데이터를 채우는 방법
Time Seires Data에서 누락된 데이터를 해결하는 일반적인 방법은 크게 3가지가 있다.
01. 누락 된 데이터를 해결하는 방법
1. 대치법(imputation) : 사용자가 누락 된 데이터를 관측에 기반하여 입력해서 채워 넣는다.
2. 보간법 (interpolation) : 인접한 데이터를 사용하여 누락된 데이터를 추정한다.
3. 제거
어떤 방법을 사용할지는 데이터에 따라 다르겠지만, 나 같은 경우에는 0이나, mean, 특정 통계량을 활용 할 때에는 대치법을 활용하고, time seires의 경향성이 보이는 경우에는 보간법을 활용하고 데이터가 제거해도 관계없다고 판단 되는 경우에는 제거한다.
02. 누락 된 데이터를 해결하는데 사용하는 함수
위의 3가지 방법을 활용하기 위해서는 pandas에서 fillna, interpolate, dropna 함수를 활용할 수 있다.
- 대치법 : fillna
- 보간법 : fillna, interpolate
- 제거 : dropna
비교적 간단한 경우에는 fillna와 dropna로 해결 가능하지만 좀 더 디테일을 원한다면 interpolate를 활용하면 된다.
(1) pandas.fillna
먼저 fillna 함수를 살펴보자.
pandas.DataFrame.fillna — pandas 1.3.2 documentation
If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is t
pandas.pydata.org
공식 홈페이지의 예재를 보면
import pandas as pd
import numpy as np
df = pd.DataFrame([[np.nan, 2, np.nan, 0],
[3, 4, np.nan, 1],
[np.nan, np.nan, np.nan, 5],
[np.nan, 3, np.nan, 4]],
columns=list("ABCD"))
df.fillna(0)
fillna(0)와 같이 특정 값을 지정하여 None data를 채울 수 있다.
df.fillna(method="ffill")
이전값이나 이후값을 활용하려고 할 때에는 'method' 를 활용 할 수있는데 사용할 수 있는 옵션은
‘backfill’, ‘bfill’, ‘pad’, ‘ffill’로 4가지가 있다.
pad와 ffill : None의 이전 데이터를 활용하여 None을 채운다.
backfill, bfill : None의 다음 데이터를 활용하여 None을 채운다.
values = {"A": 0, "B": 1, "C": 2, "D": 3}
df.fillna(value=values)
칼럼별 지정된 값으로 채워줍니다.