检查Pandas DataFrame列中的字符串是否在字符串列表中

检查Pandas DataFrame列中的字符串是否在字符串列表中,第1张

检查Pandas DataFrame列中的字符串是否在字符串列表中
frame = pd.Dataframe({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']})frame       a0   the cat is blue1  the sky is green2  the dog is black

str.contains
方法接受正则表达式模式

mylist = ['dog', 'cat', 'fish']pattern = '|'.join(mylist)pattern'dog|cat|fish'frame.a.str.contains(pattern)0     True1    False2     TrueName: a, dtype: bool

由于支持正则表达式模式,因此您还可以嵌入标志:

frame = pd.Dataframe({'a' : ['Cat Mr. Nibbles is blue', 'the sky is green', 'the dog is black']})frame          a0  Cat Mr. Nibbles is blue1         the sky is green2         the dog is blackpattern = '|'.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    False2     True


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5652563.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存