Conversion of Object to float

Asked

Viewed 1,192 times

1

I have a dataframe with a column with values:

0         411,90
1         394,88
2           0,01
3           0,01

In a csv file, all the columns of my df have 'Object' typing, when I try to convert the columns that have values like the one above the python answers me with the error:

df[coluna] = df[coluna].astype(float)

ValueError: could not convert string to float: '411,90'

I tried to import the file as follows:

df = pd.read_csv('base.csv', sep=';', encoding='UTF-8')

But also I can’t convert the columns to float, anyone has any suggestions?

1 answer

2

Hello!

So this is because the number is being read as string.

I suggest you change that comma in the numbers by a dot, like this:

df['coluna'] = df['coluna'].str.replace(',','.')

Then try to perform the conversion again..

df[coluna] = df[coluna].astype(float)

or do it all in one line:

df['coluna'] = df['coluna'].str.replace(',','.').astype(float)

I hope I’ve helped! =]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.