rsplit 在 pandas 系列上使用正则表达式不起作用 [英] rsplit on pandas series with regular expression not working
问题描述
使用正则表达式对 pandas 系列进行 rsplit 不起作用.我想根据分隔符拆分系列而不删除分隔符.
df2= pd.Series(['A类系列','C类B类系列','D类','Class'])分隔符='类'数据 = df2.str.split(r'.(?='+seperator+')', n = 2, expand=True)
结果是:
<代码> 0 1 20 系列 A 类 无1 系列 B 类 C 类部分2 D 类 无 无3 类 无 无
我想用 rsplit 做同样的事情
我试过了
data = df2.str.rsplit(r'.(?='+seperator+')', n = 2, expand=True)
使用 rsplit 期待相同的结果
<代码> 0 1 20 系列 A 类 无1 系列 B 类部分 C 类2 D 类 无 无3 类 无 无
不幸的是,pd.Series.str.rsplit
无法按照文档(v0.25, stable/v1+).该项目的 GitHub 问题跟踪器有一个 open bug 从 2019 年 11 月开始报告rsplit
不适用于正则表达式模式(v 0.24.2 和 0.25.2).在内部,该方法正在调用 str.rsplit
不支持正则表达式.
幸运的是,记者 jamespreed 添加了一个(本土的)替代功能:
<块引用>def str_rsplit(arr, pat=None, n=None):如果 pat 为 None 或 len(pat) == 1:如果 n 为 None 或 n == 0:n = -1f = lambda x: x.rsplit(pat, n)别的:如果 n 为 None 或 n == -1:n = 0正则表达式 = re.compile(pat)定义 f(x):s = regex.split(x)a, b = s[:-n], s[-n:]如果不是:返回 bix = 0对于 a_ 中的 a:ix = x.find(a_, ix) + len(a_)x_ = [x[:ix]]返回 x_ + b返回 fres = _na_map(f, arr)返回资源
rsplit on pandas series using regular expression not working. I want to split the series based on separator without removing separator.
df2= pd.Series(['Series of Class A','Series of Class B part of Class C','Class D','Class'])
seperator='Class'
data = df2.str.split(r'.(?='+seperator+')', n = 2, expand=True)
result is:
0 1 2
0 Series of Class A None
1 Series of Class B part of Class C
2 Class D None None
3 Class None None
I want to do same thing using rsplit
I tried
data = df2.str.rsplit(r'.(?='+seperator+')', n = 2, expand=True)
Expecting same result using rsplit
0 1 2
0 Series of Class A None
1 Series of Class B part of Class C
2 Class D None None
3 Class None None
Unfortunately, pd.Series.str.rsplit
does not work as documented (v0.25, stable/v1+). The project's GitHub issue tracker has an open bug from Nov. 2019 that repots that rsplit
is not working with regex patterns (v 0.24.2 and 0.25.2). Internally, the method is calling str.rsplit
which does not support regular expressions.
Luckily, the reporter jamespreed added a (homegrown) alternative function:
def str_rsplit(arr, pat=None, n=None): if pat is None or len(pat) == 1: if n is None or n == 0: n = -1 f = lambda x: x.rsplit(pat, n) else: if n is None or n == -1: n = 0 regex = re.compile(pat) def f(x): s = regex.split(x) a, b = s[:-n], s[-n:] if not a: return b ix = 0 for a_ in a: ix = x.find(a_, ix) + len(a_) x_ = [x[:ix]] return x_ + b return f res = _na_map(f, arr) return res
这篇关于rsplit 在 pandas 系列上使用正则表达式不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!