[英]Check if a string in a Pandas DataFrame column is in a list of strings
[英]How to check if string in list of strings is in pandas dataframe column
我现在正在做文本分析。 我的任务是计算列表中每个“坏词”在 dataframe 列的字符串中出现的次数。 我能想到的是使用.isin()
或.contains()
检查。 但是单词列表的长度超过40000。所以循环会太慢。 有一个更好的方法吗?
虽然您说循环可能太慢,但由于列表的范围,它似乎是最有效的方法。 试图让它尽可能简单。 随意根据您的需要修改打印声明。
text = 'Bad Word test for Terrible Word same as Horrible Word and NSFW Word and Bad Word again'
bad_words = ['Bad Word', 'Terrible Word', 'Horrible Word', 'NSFW Word']
length_list = []
for i in bad_words:
count = text.count(i)
length_list.append([i, count])
print(length_list)
output:
[['Bad Word', 2], ['Terrible Word', 1], ['Horrible Word', 1], ['NSFW Word', 1]]
或者,您的 output 作为字符串可以是:
length_list = []
for i in bad_words:
count = text.count(i)
print(i + ' count: ' + str(count))
Output:
Bad Word count: 2
Terrible Word count: 1
Horrible Word count: 1
NSFW Word count: 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.