我如何在str.contains()中使用正则表达式模块(因为它支持非固定长度的后置断言)在熊猫系列中查找匹配项?我猜下面的代码返回以下错误,因为它使用了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)
答案 0 :(得分: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