python - rsplit() 无法使用正则表达式拆分列

标签 python regex pandas split strsplit

原始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

要求: 我需要使用正则表达式和 rsplit() 拆分字符串和数字。 我这里有 3 种类型的值

  1. 字符串+数字
  2. 数字
  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.splitexpand=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

关于python - rsplit() 无法使用正则表达式拆分列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62606026/

相关文章:

python - 执行数学 sigma 和的最快、最有效和 pythonic 方法是什么?

python - 行匹配标准 Python Pandas 的列的索引

regex - shell 脚本。如何使用正则表达式提取字符串

regex - 需要创建类似 gmail 的搜索语法;也许使用正则表达式?

python - Pandas Dataframe - 在特定行中选择具有特定值的列

python - 将字典转换为数据帧的一列,同时将字典行名称保留在另一列中(python)

python - 创建单行 Pandas 数据框

regex - 如何构建正则表达式来解析逗号分隔值但忽略双引号中的逗号?

pandas - Spark DataFrame是否等效于Pandas Dataframe `.iloc()`方法?

python - CartoPy 中绘制的等高线的插值方法