如何在pandas df上使用这个工作正则表达式(re)来删除冗余的非数字字符,星号(*)?

Mus*_*ser 1 python regex pandas

通过使用下面的代码,我可以使用re来更改这样的字符串:*12.2到这样的浮点数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
Run Code Online (Sandbox Code Playgroud)

但是我有一只熊猫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
Run Code Online (Sandbox Code Playgroud)

如何将上述函数应用于此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
Run Code Online (Sandbox Code Playgroud)

piR*_*red 5

简单

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
Run Code Online (Sandbox Code Playgroud)

更健壮一点

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
Run Code Online (Sandbox Code Playgroud)