Tha*_*bra 5 python pandas data-cleaning
我有一个如下所示的数据框:
plan type hour status code
A cont 0 ok 010.0
A cont 2 ok 025GWA
A cont 0 notok 010VVT
A cont 0 other 6.05
A vend 1 ok 6.01
Run Code Online (Sandbox Code Playgroud)
列代码有几个字母不同的字符串字符。最后我想将“代码”列转换为浮动。我试过:
df['code'] = df['code'].str.extract('(\d+)').astype(float)
Run Code Online (Sandbox Code Playgroud)
但这样我得到了:
plan type hour status code
A cont 0 ok 10.0
A cont 2 ok 25.0
A cont 0 notok 10.0
A cont 0 other 6.0
A vend 1 ok 6.0
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到如下结果?
plan type hour status code
A cont 0 ok 10.00
A cont 2 ok 25.00
A cont 0 notok 10.00
A cont 0 other 6.05
A vend 1 ok 6.01
Run Code Online (Sandbox Code Playgroud)
您可以考虑基于替换的方法,而不是提取。
使用str.replace,然后使用astype/to_numeric转换转换为浮点数。
df.code.str.replace('[^\d.]', '').astype(float)
Run Code Online (Sandbox Code Playgroud)
或者,
pd.to_numeric(df.code.str.replace('[^\d.]', ''), errors='coerce')
Run Code Online (Sandbox Code Playgroud)
0 10.00
1 25.00
2 10.00
3 6.05
4 6.01
Name: code, dtype: float64
Run Code Online (Sandbox Code Playgroud)
使用(\d*\.?\d*)
In [441]: df['code'].str.extract('(\d*\.?\d*)', expand=False).astype(float)
Out[441]:
0 10.00
1 25.00
2 10.00
3 6.05
4 6.01
Name: code, dtype: float64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9016 次 |
| 最近记录: |