带有词汇的Python单词袋编码

时间:2019-12-22 11:46:06

标签: python machine-learning nlp

我正在尝试在我的ML模型中实现新的列。如果在抓取的数据的文本中找到特定的单词,则应创建一个数字列。为此,我创建了一个虚拟脚本进行测试。

import pandas as pd

bagOfWords = ["cool", "place"]
wordsFound = ""

mystring = "This is a cool new place"
mystring = mystring.lower()

for word in bagOfWords:
    if word in mystring: 
        wordsFound = wordsFound + word + " "

print(wordsFound)
pd.get_dummies(wordsFound)

输出为

    cool place
0   1

这意味着有一个句子“ 0”和一个“凉爽的地方”。这是不正确的。期望是这样的:

    cool place
0   1    1

1 个答案:

答案 0 :(得分:0)

找到了一个不同的解决方案,因为我找不到前进的方向。它是一种简单的直接热编码。为此,我需要为每个单词输入一个新列,然后在数据框中添加一个新列并直接创建编码。

vocabulary = ["achtung", "suchen"]

for word in vocabulary:
    df2[word] = 0

    for index, row in df2.iterrows():
        if word in row["title"].lower():
            df2.set_value(index, word, 1)