是否有任何函数相当于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()
有更好的办法吗?
可以将
str.contains
单独与使用OR (|)
的regex模式一起使用:或者可以将序列添加到
dataframe
中,然后使用str.contains
:输出:
一种方法是使用正则表达式
|
字符来尝试匹配序列s
(仍在使用str.contains
)中单词中的每个子字符串。可以通过将
searchfor
中的单词与|
连接来构造正则表达式:正如@AndyHayden在下面的注释中所指出的,如果子字符串有一些特殊的字符,比如
$
和^
,那么请小心。这些字符在正则表达式的上下文中有特定的含义,并且会影响匹配。通过使用
re.escape
转义非字母数字字符,可以使子字符串列表更安全:与
str.contains
一起使用时,此新列表中的字符串将按字面意思匹配每个字符。相关问题 更多 >
编程相关推荐