首页 > 解决方案 > 将列从对象转换为浮点数时出现值错误

问题描述

我正在尝试将列“value $”从数据类型“Object”转换为“float”,因为该列将涉及数值计算。

我最初使用以下方法替换了本专栏中的“$”:

 df['Value $'] = df['Value $'].replace({'\$': ''},regex=True)

然后使用以下方法将其转换为数字:

 df['Value $'] = df['Value $'].astype(dtype=np.float64)

在此处输入图像描述

标签: pythonpandas

解决方案


可能是因为您也应该替换逗号:

df['Value $'] = df['Value $'].replace({'\$|,': ''}, regex=True)
df['Value $'] = df['Value $'].astype(dtype=np.float64)

推荐阅读