简体   繁体   中英

Why does .replace not work in my dataframe?

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.

Try with

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM