如何将含$与逗号的字符串列转为整数?解决Pandas转换报错
解决Pandas中带$和逗号的Price列转整数的错误
问题原因
你的正则表达式\[$,.\]仅匹配单个的$、逗号或点字符,且未处理字符串前后的空格,导致替换后仍残留$和空格(比如错误中的$4,000 ),无法直接转为整数。
解决方案
方案1:修正正则表达式+去除空格
直接用正则移除所有$和逗号,再去掉前后空白字符,最后转整数:
car_sales["Price"] = car_sales["Price"].str.replace('[\$,]', '', regex=True).str.strip().astype(int)
[\$,]:匹配所有$或逗号字符,一次性替换干净str.strip():移除字符串前后的空格(包括换行、制表符等空白)astype(int):将清理后的纯数字字符串转为整数
方案2:分步处理(更直观,兼容浮点数)
如果Price列包含浮点数(比如$3,500.50),可以分步处理后转类型:
# 自定义清理函数 def clean_price(price_str): # 移除$、逗号,去掉空格,转浮点数后转整数(保留整数部分) cleaned = price_str.replace('$', '').replace(',', '').strip() return int(float(cleaned)) car_sales["Price"] = car_sales["Price"].apply(clean_price)
如果需要保留小数,把int(float(cleaned))改成float(cleaned)即可。
方案3:用pd.to_numeric增强健壮性
Pandas的to_numeric可以自动处理类型转换,还能通过errors参数处理异常值:
import pandas as pd car_sales["Price"] = pd.to_numeric( car_sales["Price"].str.replace('[\$,]', '', regex=True).str.strip(), downcast='integer', errors='coerce' # 无法转换的值设为NaN,可根据需求调整为'raise'或'ignore' )
内容的提问来源于stack exchange,提问作者Muhammad Abdullah
相关产品推荐
相关产品推荐

