如何在pandas中测试字符串是否包含列表中的一个子字符串?

2024-09-29 19:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有任何函数相当于df.isin()df[col].str.contains()的组合?

例如,假设我有这个系列 s = pd.Series(['cat','hat','dog','fog','pet']),我想找到s包含任何['og', 'at']的所有地方,我想得到除“宠物”之外的所有东西。

我有一个解决方案,但很不雅观:

searchfor = ['og', 'at']
found = [s.str.contains(x) for x in searchfor]
result = pd.DataFrame[found]
result.any()

有更好的办法吗?


Tags: 函数dfhatcolresultatcatseries
2条回答

可以将str.contains单独与使用OR (|)的regex模式一起使用:

s[s.str.contains('og|at')]

或者可以将序列添加到dataframe中,然后使用str.contains

df = pd.DataFrame(s)
df[s.str.contains('og|at')] 

输出:

0 cat
1 hat
2 dog
3 fog 

一种方法是使用正则表达式|字符来尝试匹配序列s(仍在使用str.contains)中单词中的每个子字符串。

可以通过将searchfor中的单词与|连接来构造正则表达式:

>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0    cat
1    hat
2    dog
3    fog
dtype: object

正如@AndyHayden在下面的注释中所指出的,如果子字符串有一些特殊的字符,比如$^,那么请小心。这些字符在正则表达式的上下文中有特定的含义,并且会影响匹配。

通过使用re.escape转义非字母数字字符,可以使子字符串列表更安全:

>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']

str.contains一起使用时,此新列表中的字符串将按字面意思匹配每个字符。

相关问题 更多 >

    热门问题