Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't convert string to float because of '.'?

I need to round the string values of a column in my dataframe up to 2 decimal cases, so I started by converting them to floats using astype(float) and then using round(2).
Ex:

df['col'] = df['col'].astype(float).round(2)

But I’m getting the following error:

ValueError: could not convert string to float: '.'

I thought the dots would be no problem, is there something I’m missing here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit: It’s a huge amount of data, so there could be unexpected values, but after filtering it to testing samples the error continues.

Edit2: Turns out I still had invalid data even after filtering the sheet, so sorry for the seemingly dumb question lol. mozways’s solution worked fine.

>Solution :

To convert string to numeric without errors upon invalid data, use pandas.to_numeric:

df['col'] = pandas.to_numeric(df['col'], error='coerce').round(2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading