Skip to main content
 首页 » 编程设计

python之如何在 pandas df 上使用这个有效的正则表达式 (re) 来删除多余的非数字字符,星号 (*)

2025年05月04日28dflying

通过使用下面的代码,我可以使用 re 将这样的字符串:*12.2 更改为这样的 float :12.2:

import re 
numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?' 
rx = re.compile(numeric_const_pattern, re.VERBOSE) 
print('converted string to float number is', float(rx.findall("*12.2")[0])) 
 
converted string to float number is 12.2 

但是我有一个 pandas df,它是:

df = pd.DataFrame([[10, '*41', '-0.01', '2'],['*10.5', 54, 34.2, '*-0.076'],  
                        [65, -32.01, '*344.32', 0.01], ['*32', '*0', 5, 43]]) 
 
 
       0         1         2          3 
0      10       *41      -0.01        2 
1     *10.5      54       34.2      *-0.076 
2      65       -32.01   *344.32      0.01 
3     *32       *0        5           43 

我如何将上面的函数应用到这个 df 以删除所有星号字符并制作一个完整的 float dtype pandas df,如下所示?

       0       1       2          3 
0      10      41     -0.01       2 
1      10.5    54      34.2      -0.076 
2      65     -32.01   344.32     0.01 
3      32      0       5          43 

请您参考如下方法:

简单

df.replace('[^\d\.eE+-]', '', regex=True).astype(float) 
 
      0      1       2       3 
0  10.0  41.00   -0.01   2.000 
1  10.5  54.00   34.20  -0.076 
2  65.0 -32.01  344.32   0.010 
3  32.0   0.00    5.00  43.000 

更稳健一点

df.replace('[^\d\.eE+-]', '', regex=True).apply(pd.to_numeric, errors='coerce') 
 
      0      1       2       3 
0  10.0  41.00   -0.01   2.000 
1  10.5  54.00   34.20  -0.076 
2  65.0 -32.01  344.32   0.010 
3  32.0   0.00    5.00  43.000