Pandas:将错误字符串键入为浮点数(无法将字符串转换为浮点数:"7,50")



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

这是字段:

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

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

In: 
merged['platnosc_total'].astype(float)
Out:
ValueError: could not convert string to float: '7,50'

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

如何实际将此字段/列转换为浮动?

首先需要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

如果列中有nan行或空行,则astype(float)不起作用。

你应该尝试

merged.replace('', np.nan).dropna(subset=['platnosc_total'], inplace=True)
merged['platnosc_total'].astype(float)

最新更新