简体   繁体   中英

convert a column type 'object' to float

I have a column of numbers (type 'object') in my df:

1

2,23

5,23

200

I tried to convert using astype, but an error tells me that they cannot convert with commas, so I tried using

df[column].str.replace(',','.', inplace=True)

but the results tranformed all values without comma into NaNs..

So I tried another solution:

mask=df[column].str.contains(',',na=false) 
df.loc[mask].str.replace(',','.',inplace=True)

But an error message tells me that a dataframe has no str function, what could I do?

I have tried and df[column] = df[column].str.replace(',','.').astype(float) works fine for me.

I've found a solution for share:

mask=df[column].str.contains(',',na=False)
df[column]=df[column].mask(mask,df[column].str.replace(',','.'))

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