在python中过滤包含一组字符串的数据帧行

Aka*_*mar 3 python python-3.x pandas

我有一个数据框df像 -

A      B
12     A cat
24     The dog
54     An elephant
Run Code Online (Sandbox Code Playgroud)

我必须根据包含字符串列表的 B 列上的值过滤行。我可以对字符串“cat”执行以下操作:

df[df["B"].str.contains("cat", case=False, na=False)]
Run Code Online (Sandbox Code Playgroud)

这将返回我

A      B
12     A cat
Run Code Online (Sandbox Code Playgroud)

但现在我想过滤它的字符串列表,即 ['cat', 'dog',.....]。

A      B
12     A cat
24     The dog
Run Code Online (Sandbox Code Playgroud)

我可以使用 for 循环来做到这一点,但我正在寻找一种 Pandas 方法来做到这一点。我正在使用 python3 和 pandas,并且自过去 2 天以来已经搜索了很多关于堆栈溢出的解决方案

jez*_*ael 5

使用joinwith |for regex ORwith \bfor word bound:

L = ['cat', 'dog']
pat = r'(\b{}\b)'.format('|'.join(L))
df[df["B"].str.contains(pat, case=False, na=False)]
Run Code Online (Sandbox Code Playgroud)