检查 Pandas DataFrame 列中的字符串是否在字符串列表中
- 2025-03-04 08:23:00
- admin 原创
- 98
问题描述:
如果我有这样的框架
frame = pd.DataFrame({
"a": ["the cat is blue", "the sky is green", "the dog is black"]
})
并且我想检查其中任何一行是否包含某个单词,我只需要这样做。
frame["b"] = (
frame.a.str.contains("dog") |
frame.a.str.contains("cat") |
frame.a.str.contains("fish")
)
frame["b"]
输出:
0 True
1 False
2 True
Name: b, dtype: bool
如果我决定列一个清单:
mylist = ["dog", "cat", "fish"]
我如何检查行是否包含列表中的某个单词?
解决方案 1:
frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']})
frame
a
0 the cat is blue
1 the sky is green
2 the dog is black
该str.contains
方法接受正则表达式模式:
mylist = ['dog', 'cat', 'fish']
pattern = '|'.join(mylist)
pattern
'dog|cat|fish'
frame.a.str.contains(pattern)
0 True
1 False
2 True
Name: a, dtype: bool
由于支持正则表达式模式,您还可以嵌入标志:
frame = pd.DataFrame({'a' : ['Cat Mr. Nibbles is blue', 'the sky is green', 'the dog is black']})
frame
a
0 Cat Mr. Nibbles is blue
1 the sky is green
2 the dog is black
pattern = '|'.join([f'(?i){animal}' for animal in mylist]) # python 3.6+
pattern
'(?i)dog|(?i)cat|(?i)fish'
frame.a.str.contains(pattern)
0 True # Because of the (?i) flag, 'Cat' is also matched to 'cat'
1 False
2 True
解决方案 2:
对于列表应该有效
print(frame[frame["a"].isin(mylist)])
看pandas.DataFrame.isin()
。
解决方案 3:
在阅读了提取字符串的已接受答案的评论后,也可以尝试这种方法。
frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']})
frame
a
0 the cat is blue
1 the sky is green
2 the dog is black
让我们创建包含需要匹配和提取的字符串的列表。
mylist = ['dog', 'cat', 'fish']
pattern = '|'.join(mylist)
现在让我们创建一个负责查找和提取子字符串的函数。
import re
def pattern_searcher(search_str:str, search_list:str):
search_obj = re.search(search_list, search_str)
if search_obj :
return_str = search_str[search_obj.start(): search_obj.end()]
else:
return_str = 'NA'
return return_str
我们将此函数与 pandas.DataFrame.apply 一起使用
frame['matched_str'] = frame['a'].apply(lambda x: pattern_searcher(search_str=x, search_list=pattern))
结果 :
a matched_str
0 the cat is blue cat
1 the sky is green NA
2 the dog is black dog
解决方案 4:
例如,我们可以使用管道同时检查三种模式,
for i in range(len(df)):
if re.findall(r'car|oxide|gen', df.iat[i,1]):
df.iat[i,2]='Yes'
else:
df.iat[i,2]='No'
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD