2024-09-30 06:26:08 发布
网友
我在一个数据帧中有一系列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.+?(?=\|)
经过多次尝试,我终于走到了这一步。。我错过了什么
更有效的模式可能是匹配字符串开头的非数字
然后捕获组1(将用于新列)中的第一个数字,并进行匹配,直到第一次遇到管道|,而不是使用前瞻
\A\D*(\d+)[^|]*\|
\A
\D*
(\d+)
[^|]*\|
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()
dataframe
extract()
要做到这一点,我们需要通过在()之间封装模式,将上面的regex放在捕获组中
()
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
更有效的模式可能是匹配字符串开头的非数字
然后捕获组1(将用于新列)中的第一个数字,并进行匹配,直到第一次遇到管道
|
,而不是使用前瞻\A
字符串的开头\D*
匹配可选的非数字(\d+)
捕获组1,匹配1+个数字[^|]*\|
匹配除|
之外的任何字符,然后匹配|
Regex demo
示例代码
输出
你可以用
唯一的改变是在管道前面的lookahead中添加
.*
,以查找管道后面的任何内容要在
dataframe
中利用此函数创建一个只包含数字的新列,我们可以使用extract()
要做到这一点,我们需要通过在
()
之间封装模式,将上面的regex
放在捕获组中代码
输出
相关问题 更多 >
编程相关推荐