使用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
相关产品推荐
相关产品推荐

