python - rsplit() 无法使用正则表达式拆分列
问题描述
原始df
import pandas as pd
df = pd.DataFrame({
'Ref':['CU12','SE00', 'RLA1234', 'RLA456', 'LU00', 'RLA1234MA12','RLA1234MA13', 'CU00','LU00']
} )
Ref
0 CU12
1 SE00
2 RLA1234
3 12345
4 RLA456
5 LU00
6 RLA1234MA12
7 RLA1234MA13
8 CU00
9 LU00
要求:我需要使用 regex 和 rsplit() 拆分字符串和数字。我这里有 3 种类型的值
- 字符串 + 数字
- 数字
- 字符串 + 数字 + 字符串 + 数字。我需要 rsplit() 并只从右边获取数字,然后是字符串的其余部分所以,
CU12 应该给出 CU 和 12 , RLA1234MA12 应该给出 RLA1234MA 和 12 , 12345 应该给出 12345。
split() 工作正常并正确拆分列,但是当涉及到 rsplit() 时,我的正则表达式无法生成所需的列。我确实阅读了 split() 和 rsplit() 的文档。这是我尝试过的。我的 df 看起来像这样
result = df['Ref'].str.split('([A-Za-z]*)(\d*)', expand=True)
这给了我
0 1 2 3 4 5 6 7 8 9
0 CU 12 None None None
1 SE 00 None None None
2 RLA 1234 None None None
3 12345 None None None
4 RLA 456 None None None
5 LU 00 None None None
6 RLA 1234 MA 12
7 RLA 1234 MA 13
8 CU 00 None None None
9 LU 00 None None None
我只需要在我的结果中得到 2 列,这样我就可以做这样的事情
result = result.loc[:,[1,2]]
result.rename(columns={1:'x', 2:'y'}, inplace=True)
print(result)
x y
0 CU 12
1 SE 00
2 RLA 1234
3 12345
4 RLA 456
5 LU 00
6 RLA1234MA 12
7 RLA1234MA 13
8 CU 00
9 LU 00
但是当我使用 rsplit() 时,我的列不会像在 split() 中那样拆分。
我现在唯一的选择是在我的列上使用 apply 并编写一个自定义函数,该函数将从末尾遍历字符串并在找到字符后立即对其进行切片。有没有使用 rsplit() 的方法。我哪里错了?
解决方案
与具有命名捕获组Series.str.extract
的给定模式一起使用:regex
result = df['Ref'].str.extract(r'(?P<x>\w*?)(?P<y>\d*)$')
或者,也可以使用Series.str.split
with expand=True
:
result = df['Ref'].str.split(r'(?<!\d)(?=\d+$)', expand=True)
结果:
# print(result)
x y
0 CU 12
1 SE 00
2 RLA 1234
3 12345
4 RLA 456
5 LU 00
6 RLA1234MA 12
7 RLA1234MA 13
8 CU 00
9 LU 00
测试regex
模式here
。