Pandas:astype error string to float(无法将字符串转换为浮点数:'7,50')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44966528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:56:25  来源:igfitidea点击:

Pandas: astype error string to float (could not convert string to float: '7,50')

pythonpandas

提问by FilipB

I am trying to convert a dataframe field from string to float in Pandas.

我正在尝试将数据帧字段从字符串转换为 Pandas 中的浮点数。

This is the field:

这是字段:

In:

print(merged['platnosc_total'].head(100))

Out:

0     0,00
1     4,50
2     0,00
3     0,00
4     0,00
5     4,50
6     6,10
7     7,99
8     4,00
9     7,69
10    7,50

Note the 7,50, in the last row, which seems to cause the error:

请注意最后一行中的 7,50,这似乎导致了错误:

In: 

merged['platnosc_total'].astype(float)

Out:

ValueError: could not convert string to float: '7,50'

Does this mean that the rest got converted, and only the row with 7,50 is the cause?

这是否意味着其余的都被转换了,只有 7,50 的行是原因?

How can I actually cast this field/column to float?

我如何才能真正将此字段/列转换为浮动?

回答by jezrael

Need replacefirst:

replace首先需要:

print (merged['platnosc_total'].replace(',','.', regex=True).astype(float))
0    0.00
1    4.50
2    0.00
3    0.00
4    0.00
5    4.50
6    6.10
7    7.99
8    4.00
Name: platnosc_total, dtype: float64