簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM