![](/img/trans.png)
[英]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.