【问题标题】:Can I use re2 library with pandas?我可以将 re2 库与熊猫一起使用吗?
【发布时间】:2020-11-05 19:46:32
【问题描述】:

我在 Python 3 中使用 re2 库,使用这个库: https://github.com/andreasvc/pyre2

我想在这个例子中在 pandas 中使用这个库:

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

这个例子可以同时使用 pandas 和 re2 库吗?

【问题讨论】:

  • 使用 pandas_series.apply 并使用 RE2 正则表达式传递自定义方法。
  • 我知道这个选项,但是,它的性能较低?
  • 没有其他选项,因为pandas 正则表达式方法使用re

标签: python regex pandas re re2


【解决方案1】:

由于 Pandas 正则表达式方法使用 re,您只能使用 apply 并使用 RE2 正则表达式传递自定义方法。

你可以使用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-27
    • 2023-03-25
    • 2020-08-04
    • 2018-10-23
    • 2011-02-22
    • 2021-03-16
    • 2016-11-20
    • 2019-01-25
    相关资源
    最近更新 更多