# 범주형 데이터의 최빈값으로 채우기
df['column_name'].fillna(df['column_name'].mode()[0],inplace=True)
앞/뒤 값으로 채우기
1
2
3
4
5
# 앞의 값으로 채우기 (forward fill)
df.fillna(method='ffill',inplace=True)# 뒤의 값으로 채우기 (backward fill)
df.fillna(method='bfill',inplace=True)
3. 보간법 (Interpolation)
1
2
3
4
5
# 선형 보간
df['column_name'].interpolate(method='linear',inplace=True)# 시계열 데이터 보간
df['column_name'].interpolate(method='time',inplace=True)
결측치 처리 전략
결측치 비율에 따른 전략
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
importpandasaspd# 결측치 비율 계산
missing_ratio=df.isnull().sum()/len(df)*100print(missing_ratio)# 결측치 비율에 따른 처리
ifmissing_ratio<5:# 5% 미만: 행 삭제
df=df.dropna()elifmissing_ratio<30:# 5-30%: 평균/중앙값으로 채우기
df.fillna(df.mean(),inplace=True)else:# 30% 이상: 해당 열 삭제 고려
df=df.drop(columns=['column_name'])
importpandasaspd# 데이터 로드
coffee_text_review=pd.read_csv('coffee_reviews.csv')# 1. 결측치 확인
print("결측치 개수:")print(coffee_text_review.isnull().sum())print("\n데이터셋 크기:",coffee_text_review.shape)# 2. 결측치 비율 계산
missing_ratio=coffee_text_review.isnull().sum()/len(coffee_text_review)*100print("\n결측치 비율(%):")print(missing_ratio)# 3. 결측치 제거
coffee_drop=coffee_text_review.dropna()print("\n처리 후 데이터셋 크기:",coffee_drop.shape)# 4. 결과 확인
print("\n처리 후 결측치:")print(coffee_drop.isnull().sum())