Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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?

like image 441
FilipB Avatar asked Oct 28 '25 16:10

FilipB


2 Answers

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
like image 74
jezrael Avatar answered Oct 31 '25 07:10

jezrael


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)
like image 23
crisprin Avatar answered Oct 31 '25 05:10

crisprin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!