首页 > 解决方案 > 在 python 中的数据帧上应用一种热编码

问题描述

我正在处理一个数据集,其中我有各种不同值的字符串列,并且想要应用one hot encoding.

这是示例数据集:

v_4        v5             s_5     vt_5     ex_5          pfv           pfv_cat
0-50      StoreSale     Clothes   8-Apr   above 100   FatimaStore       Shoes
0-50      StoreSale     Clothes   8-Apr   0-50        DiscountWorld     Clothes
51-100    CleanShop     Clothes   4-Dec   51-100      BetterUncle       Shoes

所以,在这里我需要应用一个热编码,pvf_cat就像我有其他列一样,我已经创建了这些列的列表,这str_cols 就是我应用的方式one-hot-encoding

for col in str_cols:
    data = df[str(col)]
    values = list(data)
    # print(values)
    # integer encode
    label_encoder = LabelEncoder()
    integer_encoded = label_encoder.fit_transform(values)
    print(integer_encoded)
    # one hot encode
    encoded = to_categorical(integer_encoded)
    print(encoded)
    # invert encoding
    inverted = argmax(encoded[0])
    print(inverted)
    onehot_encoder = OneHotEncoder(sparse=False)
    integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
    onehot_encoded = onehot_encoder.fit_transform(integer_encoded)

但它不影响数据集,当我打印它时df.head()它仍然是一样的,这里有什么问题?

标签: pythonpandasdataframeone-hot-encoding

解决方案


使用pd.get_dummies()比为此编写自己的代码要容易得多,而且可能也更快。

df = pd.get_dummies(df, columns=['pfv_cat'])

      v_4         v5      s_5   vt_5       ex_5            pfv  pfv_cat_Clothes pfv_cat_Shoes
0    0-50  StoreSale  Clothes  8-apr  above 100    FatimaStore                0             1
1    0-50  StoreSale  Clothes  8-apr       0-50  DiscountWorld                1             0
2  51-100  CleanShop  Clothes  4-dec     51-100    BetterUncle                0             1

columns=参数后面的列表中,您可以指定要 OneHotEncoded 的列。所以在你的情况下,这可能是df = pd.get_dummies(df, columns=str_cols).


推荐阅读