如何检查字符串列表中的字符串是否在pandas dataframe列中

时间:2019-11-14 14:09:33

标签: python pandas

我正在做文本分析。我的任务是计算列表中的每个“坏词”出现在数据框列中的字符串中的次数。我能想到的是使用.isin().contains()逐字检查。但是单词列表的长度超过40000。因此循环将太慢。有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

虽然您说循环可能太慢,但由于列表的范围,它似乎是最有效的方法。试图使其尽可能简单。 随时根据需要修改打印语句。

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)

输出:

[['Bad Word', 2], ['Terrible Word', 1], ['Horrible Word', 1], ['NSFW Word', 1]]

或者,您的输出为字符串可以是:

length_list = []

for i in bad_words:
    count = text.count(i)
    print(i + ' count: ' + str(count))

输出:

Bad Word count: 2
Terrible Word count: 1
Horrible Word count: 1
NSFW Word count: 1