I am trying to convert a dataframe field from string to float in 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:
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?
How can I actually cast this field/column to float?
Need replace first:
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
If you have nan or empty rows in your column, astype(float) won't work.
You should try
merged.replace('', np.nan).dropna(subset=['platnosc_total'], inplace=True)
merged['platnosc_total'].astype(float)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With