python中的正则表达式模式连接

2024-05-31 23:55:14 发布

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

我有以下模式来匹配以下案例中的百分比

76.39% (based on 206 issue)
1.23% (based on 197)
81.06% based on 206,390,020 fully  issue
12.02
16.59
81.61%
45
24.812
51.35
19348952
88.22
0
000
021
.85%
100
1 67.08% 
2 70.98%

预期:

76.39
1.23
81.06
12.02
16.59
81.61
45
24.812
51.35

88.22
0
000
21
.85
100
67.08
70.98
pattern1= r'(\d+\.\d+%)'
df['var']=df['var'].astype(str).str.extract(pattern1)[0]


pattern2 = r'^(?:0{0,})((?:[1-9]{1,2}|100)?(?:\.\d+)?)%?$'
df['var']=df['var'].astype(str).str.extract(pattern2)[0]

是否有任何方法可以将它们组合成单个正则表达式模式以匹配所有情况

注意:我使用的示例案例只是许多独特百分比类型的一小部分。所以我需要一个只提取百分比(最多2个小数点)的解决方案。其中的一些特征包括-*在%;%其次是百分率的百分率;;有时,诸如*@#之类的特殊字符在百分比之前和之后

谢谢你的帮助。多谢各位


Tags: dfonvar模式extractissue案例based
1条回答
网友
1楼 · 发布于 2024-05-31 23:55:14

您只能使用正则表达式在%或空格上拆分,然后将float应用于第一项:

import pandas as pd
import numpy as np
import string

data ='''76.39% (based on 206 issue)
1.23% (based on 197)
81.06% based on 206,390,020 fully  issue
12.02
16.59
81.61%
45
24.812
51.35
19348952
88.22
0
000
021
.85%
100'''

df = pd.DataFrame(data.splitlines(), columns=['text'])
df['var'] = df['text'].str.strip(string.punctuation + string.ascii_letters).str.split(r'%|\s').str[0].astype(float).apply(lambda x: x if x <= 100.0 else np.nan)

输出:

^{tb1}$

相关问题 更多 >