1

如何使用带有 str.contains() 的正则表达式模块(因为它支持非固定长度的lookbehind断言)在熊猫系列中查找匹配项?下面的代码返回以下错误,我猜是因为它使用了 re 模块:TypeError: first argument must be string or compiled pattern.

import pandas as pd
import regex
to_test = pd.Series([ 'yes' , 'no' , 'yes' ])
classifier = regex.compile(r"yes")
result = to_test.str.contains(classifier)
4

1 回答 1

1

您可以定义自己的方法regex_search并使用apply()

import pandas as pd
import regex

to_test = pd.Series([ 'yes' , 'no' , 'yes' ])

def regex_contains(s, rx):
    return bool(rx.search(s))

classifier = regex.compile(r"yes")
to_test.apply(regex_contains, args=(classifier,))

输出:

0     True
1    False
2     True
dtype: bool
于 2020-04-28T16:54:19.313 回答