我有一个字符串列表。我想统计熊猫列中每一行中所有单词的出现,并以此计数添加新列。
words = ["I", "want", "please"]
data = pd.DataFrame({"col" : ["I want to find", "the fastest way", "to
count occurrence", "of words in a column", "Can you help please"]})
data["Count"] = data.col.str.count("|".join(words))
print(data)
这里显示的代码完全可以实现我想要的功能,但是要花很长时间才能运行很长的文本和很长的单词列表。你能建议一种更快的方法来做同样的事情吗?
谢谢
答案 0 :(得分:2)
也许您可以使用Counter
。如果您有多组words
来针对同一文本进行测试,则只需在应用Counter
之后保存中间步骤。由于这些计数的单词现在位于以该单词为键的词典中,因此,测试该词典是否包含给定单词是O(1)操作。
from collections import Counter
data["Count"] = (
data['col'].str.split()
.apply(Counter)
.apply(lambda counts: sum(word in counts for word in words))
)
>>> data
col Count
0 I want to find 2
1 the fastest way 0
2 to count occurrence 0
3 of words in a column 0
4 Can you help please 1