Pandas 使用每个示例的多个类别对分类功能进行编码-sklearn

Pandas 使用每个示例的多个类别对分类功能进行编码-sklearn,pandas,machine-learning,scikit-learn,feature-extraction,categorical-data,Pandas,Machine Learning,Scikit Learn,Feature Extraction,Categorical Data,我正在制作一个电影数据集,其中包含流派作为一个功能。数据集中的示例可能同时属于多个类型。因此,它们包含了一系列类型标签 数据如下所示- movieId genres 0 1 [Adventure, Animation, Children, Comedy, Fantasy] 1 2 [Adventure, Children, Fantasy]

我正在制作一个电影数据集,其中包含流派作为一个功能。数据集中的示例可能同时属于多个类型。因此,它们包含了一系列类型标签

数据如下所示-

    movieId                                         genres
0        1  [Adventure, Animation, Children, Comedy, Fantasy]
1        2                     [Adventure, Children, Fantasy]
2        3                                  [Comedy, Romance]
3        4                           [Comedy, Drama, Romance]
4        5                                           [Comedy]
我想将此功能矢量化。我试过LabelEncoder和OneHotEncoder,但它们似乎无法直接处理这些列表

我可以手动将其矢量化,但我有其他类似的功能,其中包含太多的类别。对于那些我更喜欢直接使用FeatureHasher类的方法

有没有办法让这些编码器类处理这样的功能?或者有没有更好的方法来表示这样一个特性,从而使编码更容易?我很乐意接受任何建议。

有一些令人印象深刻的答案。在您的示例数据中,Teoretic的最后一个答案(使用
sklearn.preprocessing.multi-labelbinarizer
)比Paulo Alves的解决方案快14倍(两者都比公认的答案快!):

from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
encoded = pd.DataFrame(mlb.fit_transform(df['genres']), columns=mlb.classes_, index=df.index)
result = pd.concat([df['movieId'], encoded], axis=1)

# Increase max columns to print the entire resulting DataFrame
pd.options.display.max_columns = 50
result
   movieId  Adventure  Animation  Children  Comedy  Drama  Fantasy  Romance
0        1          1          1         1       1      0        1        0
1        2          1          0         1       0      0        1        0
2        3          0          0         0       1      0        0        1
3        4          0          0         0       1      1        0        1
4        5          0          0         0       1      0        0        0