首页 > 解决方案 > Pandas str.split 不剥离分割模式

问题描述

示例代码:

In [1]: import pandas as pd

In [2]: serie = pd.Series(['this#is#a#test', 'another#test'])

In [3]: serie.str.split('#', expand=True)
Out[3]:
         0     1     2     3
0     this    is     a  test
1  another  test  None  None

是否可以在不剥离拆分条件字符串的情况下拆分?上述输出将是:

Out[3]:
         0     1     2     3
0     this   #is    #a #test
1  another #test  None  None

编辑 1:真正的用例是保持匹配模式,例如:

serie.str.split(r'\n\*\*\* [A-Z]+', expand=True)

在我的情况下,[AZ]+ 是处理步骤,我想保留这些步骤以供进一步处理。

标签: pythonregexpandas

解决方案


你可以通过积极的展望来分裂。因此,分割点将是 postivie 前瞻表达式之前的点。

import pandas as pd

serie = pd.Series(['this#is#a#test', 'another#test'])
print(serie.str.split('(?=#)', expand=True))

输出

         0      1     2      3
0     this    #is    #a  #test
1  another  #test  None   None

推荐阅读