正则表达式捕获第一个数字组

2024-09-30 06:26:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个数据帧中有一系列str值:

S10|1828575
S10|1828575
S10|1828575
S10|1828575
SA510KPBF|47010705
SA510KPBF|47010705
SABLF|47009610
SABLF|47009610
SABLF|47009610

我想捕获|之前的所有数值

预期:

10
10
10
10
510
510

使用:

\d.+?(?=\|)

经过多次尝试,我终于走到了这一步。。我错过了什么

enter image description here


Tags: 数据数值strs10sablfsa510kpbf
2条回答

更有效的模式可能是匹配字符串开头的非数字

然后捕获组1(将用于新列)中的第一个数字,并进行匹配,直到第一次遇到管道|,而不是使用前瞻

\A\D*(\d+)[^|]*\|
  • \A字符串的开头
  • \D*匹配可选的非数字
  • (\d+)捕获组1,匹配1+个数字
  • [^|]*\|匹配除|之外的任何字符,然后匹配|

Regex demo

示例代码

import pandas as pd

strings = ['S10|1828575',
     'S10|1828575',
     'S10|1828575',
     'S10|1828575',
     'SA510KPBF|47010705',
     'SA510KPBF|47010705',
     'SABLF|47009610',
     'SABLF|47009610',
     'SABLF|47009610']

df = pd.DataFrame(strings, columns=["str_values"])
df['first_numeric'] = df["str_values"].str.extract(r'\A\D*(\d+)[^|]*\|')
print(df)

输出

           str_values first_numeric
0         S10|1828575            10
1         S10|1828575            10
2         S10|1828575            10
3         S10|1828575            10
4  SA510KPBF|47010705           510
5  SA510KPBF|47010705           510
6      SABLF|47009610           NaN
7      SABLF|47009610           NaN
8      SABLF|47009610           NaN

你可以用

\d+(?=.*\|)

唯一的改变是在管道前面的lookahead中添加.*,以查找管道后面的任何内容


要在dataframe中利用此函数创建一个只包含数字的新列,我们可以使用extract()

要做到这一点,我们需要通过在()之间封装模式,将上面的regex放在捕获组中

r'(\d+(?=.*\|))'

代码

d = ['S10|1828575',
'S10|1828575',
'S10|1828575',
'S10|1828575',
'SA510KPBF|47010705',
'SA510KPBF|47010705',
'SABLF|47009610',
'SABLF|47009610',
'SABLF|47009610']

df = pd.DataFrame(data=d)

df['numbers'] = df[0].str.extract(r'(\d+(?=.*\|))')

输出

>>> df
                    0 numbers
0         S10|1828575      10
1         S10|1828575      10
2         S10|1828575      10
3         S10|1828575      10
4  SA510KPBF|47010705     510
5  SA510KPBF|47010705     510
6      SABLF|47009610     NaN
7      SABLF|47009610     NaN
8      SABLF|47009610     NaN

相关问题 更多 >

    热门问题