我可以和Pandas一起使用re2图书馆吗?

2024-06-17 17:19:27 发布

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

我正在使用re2库和Python 3,并使用以下库: https://github.com/andreasvc/pyre2

在本例中,我想在熊猫内部使用此库:

pandas_series.str.contains(regex, case=False)

在本例中,可以同时使用熊猫和re2库吗


Tags: httpsgithubcomfalsepandasregexseriescase
1条回答
网友
1楼 · 发布于 2024-06-17 17:19:27

由于Pandas regex方法使用re,因此只能使用apply并使用RE2 regex传递自定义方法

你可以用

import pandas as pd
import re2
df = pd.DataFrame({'test': [ 'abc' , 'def' , '123' ]})
def re2_contains(s, rx):
    return bool(rx.search(s))

rex = re2.compile(r'^[a-z]+$')
>>> df['test'].apply(lambda x: re2_contains(x, rex))
0     True
1     True
2    False
Name: test, dtype: bool

相关问题 更多 >