python - 在 scikit-learn 中对一列字符串中的术语进行向量化
问题描述
我有一个具有以下结构的类似表格的数据集:每一行都有,作为列:
RecipeName: "Guacamole"
Ingredients: "Avocado, vinegar, tomato"
PreparationTime: 10
我想将其转换为 pandas DataFrame 中的词袋类型表示,以便这一行变为
(column names) RecipeName Avocado Broccoli Chocolate Tomato Vinegar Zucchini
Guacamole 1 0 0 1 0 0
WeirdCacao 0 0 1 1 0 0
(我显然能够使用单个成分列的 DataFrame 并将其转换为列表的字典:
recipe_dict = {recipes.ix[m]['RecipeName']:recipes.ix[m]['Ingredients'].split(',') for m in recipes.index}
但我无法使用 CountVectorizer 。也许这甚至不是最好的处理方式。)
解决方案
我强行回答了这个特定问题;但我仍然想知道如何使用 scikit-learn 来做到这一点,因为我可能想稍后切换到 tf-idf,例如。
鉴于获得的字典
recipe_dict = {recipes.ix[m]['RecipeName']:recipes.ix[m]['Ingredients'].split(',') for m in recipes.index}
我们执行以下操作:
from functools import reduce
ingredients = reduce(lambda x, y: x+y, recipe_dict.values())
获取所有成分的列表,然后循环
for j in ingredients:
recipes[j] = recipes['RecipeName'].apply(lambda i: 1 if j in recipe_dict[i] else 0)
推荐阅读
- reactjs - 如何解决从 mongodb 中删除项目的问题?
- vue.js - 如何获取组件 q-toolbar-title 的文本?
- metrics - 如何同时添加 sum() 和 avg()?
- javascript - 使用保存按钮在新工作表中自动复制数据
- javascript - 使用 webcomponent 中的 prismjs 显示带有语法突出显示的代码片段
- javascript - HTML、Javascript:读出单元格输入,设置为选择
- python - 是否可以使用 python 截取网站的屏幕截图而不必在我的电脑上实际打开网站?
- wordpress - 如何在 WooCommerce 的自定义下拉列表中添加“按产品标签按字母顺序排序”?
- r - R中带有“ldpy”的多重线性回归问题
- angular - 我们如何在 Angular 前端进行密码确认?