我有一个字符串列表。我想要计算Pandas列的每一行中所有单词的出现次数,并使用此计数添加一个新列。
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)这里显示的代码做的正是我想要的,但是对于很长的文本和很长的单词列表,运行它需要很长的时间。你能建议一种更快的方法来做同样的事情吗?
谢谢
发布于 2019-10-26 01:45:26
也许你可以使用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 1https://stackoverflow.com/questions/58563181
复制相似问题