Home > Back-end >  Why does .replace not work in my dataframe?
Why does .replace not work in my dataframe?

Time:12-14

I have code roughly like this:

df[['floatcol1', 'floatcol2', 'floatcol3']] = df[['floatcol1', 'floatcol2', 'floatcol3']].astype(str)

df[['strfloatcol1', 'strfloatcol2', 'strfloatcol3']] = df[['strfloatcol1', 'strfloatcol2', 'strfloatcol3']].replace(',', '.')

But it is still printing my values like 527,1 and 847,9 instead of 527.2 and 847.9 like I want. I'm confused why replace isn't replacing the commas.

CodePudding user response:

Try with

df[['strfloatcol1', 'strfloatcol2', 'strfloatcol3']].replace({',':'.'}, regex=True, inplace=True)

CodePudding user response:

I got it. You have to use:

df['col'] = df['col'].str.replace(',', '.', regex=True).astype(float)

for each column. If you pass in a list of columns, Python can't convert a list into a string. There may be an easier, more effective way, but I only have three columns to convert.

  • Related