填补分类值

在 Python 中处理缺失数据

Suraj Donthi

Deep Learning & Computer Vision Consultant

分类值的复杂性

  • 大多分类值为字符串
  • 不能直接对字符串运算
  • 需将字符串转换/编码为数值再填补
在 Python 中处理缺失数据

转换方法

独热编码(One-hot encoder)
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
序数编码(Ordinal encoder)
Color Value
Red 0
Green 1
Blue 2
Red 0
Blue 2
Blue 2
在 Python 中处理缺失数据

填补方法

  • 用最频繁类别填充
  • 用统计模型(如 KNN)填补
在 Python 中处理缺失数据

用户画像数据

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
在 Python 中处理缺失数据

序数编码

from sklearn.preprocessing import OrdinalEncoder

# Create Ordinal Encoder ambience_ord_enc = OrdinalEncoder() # Select non-null values in ambience ambience = users['ambience'] ambience_not_null = ambience[ambience.notnull()] reshaped_vals = ambience_not_null.values.reshape(-1, 1)
# Encode the non-null values of ambience encoded_vals = ambience_ord_enc.fit_transform(reshaped_vals)
# Replace the ambience column with ordinal values users.loc[ambience.notnull(), 'ambience'] = np.squeeze(encoded_vals)
在 Python 中处理缺失数据

序数编码

# Create dictionary for Ordinal encoders
ordinal_enc_dict = {}

# Loop over columns to encode
for col_name in users:
    # Create ordinal encoder for the column
    ordinal_enc_dict[col_name] = OrdinalEncoder()
    col = users[col_name]

    # Select the non-null values in the column
    col_not_null = col[col.notnull()]
    reshaped_vals = col_not_null.values.reshape(-1, 1)

    # Encode the non-null values of the column
    encoded_vals = ordinal_enc_dict[col_name].fit_transform(reshaped_vals)

    # Replace the values in the column with ordinal values
    users.loc[col.notnull(), col_name] = np.squeeze(encoded_vals)
在 Python 中处理缺失数据

用 KNN 填补

users_KNN_imputed = users.copy(deep=True)

# Create KNN imputer KNN_imputer = KNN()
users_KNN_imputed.iloc[:, :] = np.round(KNN_imputer.fit_transform(users))
for col_name in users_KNN_imputed: # Reshape the values to 2-dimensions to # avoid errors while storing in the DataFrame reshaped = users_KNN_imputed[col_name].values.reshape(-1, 1) users_KNN_imputed[col_name] = \ ordinal_enc_dict[col_name].inverse_transform(reshaped)
在 Python 中处理缺失数据

小结

填补分类值的步骤

  • 将非缺失的分类列转为序数值
  • 在序数化的 DataFrame 中填补缺失值
  • 将序数值还原为分类值
在 Python 中处理缺失数据

Passons à la pratique !

在 Python 中处理缺失数据

Preparing Video For Download...