我有一列数据包含文本和我希望与文本列匹配的单个单词列表,并总结单词在每行中出现的次数。
以下是一个例子:
wordlist = ['alaska', 'france', 'italy']
test = pd.read_csv('vacation text.csv')
test.head(4)
Index Text
0 'he's going to alaska and france'
1 'want to go to italy next summer'
2 'germany is great!'
4 'her parents are from france and alaska but she lives in alaska'
我尝试使用以下代码:
test['count'] = pd.Series(test.text.str.count(r).sum() for r in wordlist)
这段代码:
test['count'] = pd.Series(test.text.str.contains(r).sum() for r in wordlist)
问题是总和似乎没有准确反映text
列中的单词数。我注意到这一点,当我再次使用我的例子时,将germany
添加到我的列表中,然后总和没有从0变为1.
最终我希望我的数据看起来像:
Index Text Count
0 'he's going to alaska and france' 2
1 'want to go to italy next summer' 1
2 'germany is great!' 0
4 'her folks are from france and italy but she lives in alaska' 3
有谁知道其他任何方法?
答案 0 :(得分:2)
一种方法是使用str.count
In [792]: test['Text'].str.count('|'.join(wordlist))
Out[792]:
0 2
1 1
2 0
3 3
Name: Text, dtype: int64
另一种方式,sum
个别字数
In [802]: pd.DataFrame({w:test['Text'].str.count(w) for w in wordlist}).sum(1)
Out[802]:
0 2
1 1
2 0
3 3
dtype: int64
详细
In [804]: '|'.join(wordlist)
Out[804]: 'alaska|france|italy'
In [805]: pd.DataFrame({w:test['Text'].str.count(w) for w in wordlist})
Out[805]:
alaska france italy
0 1 1 0
1 0 0 1
2 0 0 0
3 2 1 0