You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas转换价格为整数时触发ValueError错误求助

DataFrame Price列转整数报错的解决办法

问题根源

你写的正则替换没生效,导致原始字符串$4,000.00直接被拿去转int,自然触发ValueError。原因是pandas的str.replace()在新版本里默认把第一个参数当普通字符串匹配,不会解析正则表达式。

可行解决方法

方法1:开启正则匹配

给str.replace()加上regex=True参数,让正则规则生效:

car_sales["Price"] = car_sales["Price"].str.replace('[\$\,]|\.\d*', '', regex=True).astype(int)

方法2:分步清理更直观

拆分替换步骤,降低出错概率:

# 先去掉$和逗号
car_sales["Price"] = car_sales["Price"].str.replace('$', '', regex=False).str.replace(',', '', regex=False)
# 截断小数部分后转整数
car_sales["Price"] = car_sales["Price"].str.split('.').str[0].astype(int)

方法3:用pd.to_numeric简化流程

借助pandas内置的数值转换工具,处理更健壮:

import pandas as pd
# 先清理$和逗号,再转数值后取整
car_sales["Price"] = pd.to_numeric(car_sales["Price"].str.replace('[\$\,]', '', regex=True)).astype(int)

验证步骤

修改后可以先打印前几行数据确认清理结果:

print(car_sales["Price"].head())

内容的提问来源于stack exchange,提问作者sophie_ttee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 19:00:58