[英]convert a column type 'object' to float
I have a column of numbers (type 'object') in my df:我的df中有一列数字(类型'object'):
1 1
2,23 2,23
5,23 5,23
200 200
I tried to convert using astype, but an error tells me that they cannot convert with commas, so I tried using我尝试使用 astype 进行转换,但一个错误告诉我他们无法使用逗号进行转换,所以我尝试使用
df[column].str.replace(',','.', inplace=True)
but the results tranformed all values without comma into NaNs..但结果将所有不带逗号的值转换为 NaN..
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?但是一条错误消息告诉我 dataframe 没有 str function,我该怎么办?
I have tried and df[column] = df[column].str.replace(',','.').astype(float)
works fine for me.我已经尝试过df[column] = df[column].str.replace(',','.').astype(float)
对我来说很好。
I've found a solution for share:我找到了分享的解决方案:
mask=df[column].str.contains(',',na=False)
df[column]=df[column].mask(mask,df[column].str.replace(',','.'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.