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

如何将含$与逗号的字符串列转为整数?解决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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:16:14