首页 > 解决方案 > 在 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 。也许这甚至不是最好的处理方式。)

标签: pythonpandasscikit-learntext-mining

解决方案


我强行回答了这个特定问题;但我仍然想知道如何使用 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) 

推荐阅读