pandas - 每个示例使用多个类别编码分类特征 - sklearn
问题描述
我正在研究一个包含流派作为特征的电影数据集。数据集中的示例可能同时属于多个流派。因此,它们包含流派标签列表。
数据看起来像这样——
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的方式类的方法。
有没有办法让这些编码器类在这样的特性上工作?或者有没有更好的方法来表示这样一个特征,这将使编码更容易?我很乐意欢迎任何建议。
解决方案
这个 SO question有一些令人印象深刻的答案。在您的示例数据中,Teoretic 的最后一个答案(使用sklearn.preprocessing.MultiLabelBinarizer
)比 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
推荐阅读
- php - 尝试使用控制器方法删除文件夹时如何调试 AJAX 响应中的错误?
- html - 元素按钮不能作为a元素的后代出现如何解决
- java - 在调度程序 servlet 中添加通配符以映射 URI
- c# - 如何知道被点击的Bot框架中Action.OpenUrl的url?
- r - NormalizeData.default 在 R 中的集成 seurat 对象上运行 DoubletFinder 时出错
- r - 如何用r计算日期差
- kotlin - 摇篮。块插件中的自定义函数{}
- reactjs - 重新加载后如何使渲染仍然存在?
- sql - 如何在 Postgres 中为多对多关系构建 SQL 查询选择不相关的项目?
- r - 没有任何结果数据的逻辑回归