Python에서 결측치 다루기
Suraj Donthi
Deep Learning & Computer Vision Consultant
| Color | Color_Red | Color_Green | Color_Blue |
|---|---|---|---|
| Red | 1 | 0 | 0 |
| Green | 0 | 1 | 0 |
| Blue | 0 | 0 | 1 |
| Red | 1 | 0 | 0 |
| Blue | 0 | 0 | 1 |
| Blue | 0 | 0 | 1 |
| Color | Value |
|---|---|
| Red | 0 |
| Green | 1 |
| Blue | 2 |
| Red | 0 |
| Blue | 2 |
| Blue | 2 |
users = pd.read_csv('userprofile.csv')
users.head()
smoker drink_level dress_preference ambience hijos activity budget
0 False abstemious informal family independent student medium
1 False abstemious informal family independent student low
2 False social drinker formal family independent student low
3 False abstemious informal family independent professional medium
4 False abstemious no preference family independent student medium
from sklearn.preprocessing import OrdinalEncoder# 순서형 인코더 생성 ambience_ord_enc = OrdinalEncoder() # ambience의 결측이 아닌 값 선택 ambience = users['ambience'] ambience_not_null = ambience[ambience.notnull()] reshaped_vals = ambience_not_null.values.reshape(-1, 1)# ambience의 결측이 아닌 값 인코딩 encoded_vals = ambience_ord_enc.fit_transform(reshaped_vals)# ambience 열을 순서형 값으로 교체 users.loc[ambience.notnull(), 'ambience'] = np.squeeze(encoded_vals)
# 순서형 인코더용 딕셔너리 생성
ordinal_enc_dict = {}
# 인코딩할 열 반복
for col_name in users:
# 해당 열의 순서형 인코더 생성
ordinal_enc_dict[col_name] = OrdinalEncoder()
col = users[col_name]
# 열의 결측이 아닌 값 선택
col_not_null = col[col.notnull()]
reshaped_vals = col_not_null.values.reshape(-1, 1)
# 결측이 아닌 값 인코딩
encoded_vals = ordinal_enc_dict[col_name].fit_transform(reshaped_vals)
# 열 값을 순서형 값으로 교체
users.loc[col.notnull(), col_name] = np.squeeze(encoded_vals)
users_KNN_imputed = users.copy(deep=True)# KNN 대치기 생성 KNN_imputer = KNN()users_KNN_imputed.iloc[:, :] = np.round(KNN_imputer.fit_transform(users))for col_name in users_KNN_imputed: # DataFrame 저장 오류 방지를 위해 2차원으로 재구성 reshaped = users_KNN_imputed[col_name].values.reshape(-1, 1) users_KNN_imputed[col_name] = \ ordinal_enc_dict[col_name].inverse_transform(reshaped)
범주형 값 대치 단계
Python에서 결측치 다루기