Issue
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?
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)
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.