如何从数据框中的列表列创建多热编码?

数据挖掘 喀拉斯 熊猫 数据框
2022-02-15 02:35:06

我有这样的数据框

Label   IDs
    0   [10, 1]
    1   [15]
    0   [14]

我想创建该功能的多热编码IDs它应该看起来像这样

Label ID_10 ID_1 ID_15 ID_14
  0     1     1    0     0
  1     0     0    1     0
  0     0     0    0     1

目标是将它们用作 Keras 中的功能。因此,使用 Keras API 进行这种转换也是可以接受的。

1个回答

您可以尝试使用 sklearn MultiLabelBinarizerhttps://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html):

mlb = MultiLabelBinarizer()
mlb.fit(d['IDs'])

new_col_names = ["ID_%s" % c for c in mlb.classes_]

# Create new DataFrame with transformed/one-hot encoded IDs
ids = pd.DataFrame(mlb.fit_transform(d['IDs']), columns=new_col_names)

# Concat with original `Label` column
pd.concat( [d[['Label']], ids], axis=1 )