Pandas - 从列中的浮点数中删除字符串
Pandas - Remove strings from a float number in a column
我有一个如下所示的数据框:
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
列代码有几个不同字母的字符串字符。最后我想将 'code' 列转换为浮动。
我试过了:
df['code'] = df['code'].str.extract('(\d+)').astype(float)
但是我得到了:
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
我怎样才能得到像下面这样的结果?
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
您可以考虑基于替换的方法而不是提取。
使用str.replace
,然后通过astype
/to_numeric
转换为float。
df.code.str.replace('[^\d.]', '').astype(float)
或者,
pd.to_numeric(df.code.str.replace('[^\d.]', ''), errors='coerce')
0 10.00
1 25.00
2 10.00
3 6.05
4 6.01
Name: code, dtype: float64
使用(\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
我有一个如下所示的数据框:
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
列代码有几个不同字母的字符串字符。最后我想将 'code' 列转换为浮动。 我试过了:
df['code'] = df['code'].str.extract('(\d+)').astype(float)
但是我得到了:
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
我怎样才能得到像下面这样的结果?
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
您可以考虑基于替换的方法而不是提取。
使用str.replace
,然后通过astype
/to_numeric
转换为float。
df.code.str.replace('[^\d.]', '').astype(float)
或者,
pd.to_numeric(df.code.str.replace('[^\d.]', ''), errors='coerce')
0 10.00
1 25.00
2 10.00
3 6.05
4 6.01
Name: code, dtype: float64
使用(\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