我正在尝试在我的机器学习模型中添加新的列。如果在爬取的数据文本中发现某个特定的词,就应该创建一个数值列。为此,我创建了一个测试用的虚拟脚本。
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”的条目。这是不正确的。期望的输出应该是这样的:
cool place
0 1 1
回答:
由于找不到任何进一步的方法,我找到了另一种解决方案。这是一种简单的直接独热编码。为此,我为每个需要的新词在数据框中添加一个新列,并直接创建编码。
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)