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

如何在Pandas中移除整数千位分隔符并转为有效整数

移除DataFrame中数值的千位逗号分隔符

遇到这种带逗号的数值(比如1,598),本质是这些值存储为字符串类型,直接当作整数/浮点数使用会触发类型错误,解决核心是先替换逗号,再转为数值类型,以下是几种实用方法:

1. 单独处理某一列

如果只有特定列(比如示例中的A列)存在逗号,直接针对该列操作:

import pandas as pd

# 示例DataFrame
df = pd.DataFrame({
    'A': ['1,598', '-300'],
    'B': [65.79, 46.90],
    'C': [79, 90]
})

# 替换逗号并转为整数
df['A'] = df['A'].str.replace(',', '').astype(int)

2. 批量处理所有含逗号的列

如果不确定哪些列有逗号,可自动识别字符串类型的列进行批量处理(pd.to_numeric会自动判断转为整数或浮点数):

# 遍历所有列,仅处理字符串类型的列
for col in df.columns:
    if df[col].dtype == 'object':
        # 先替换逗号,再转为数值类型
        df[col] = pd.to_numeric(df[col].str.replace(',', ''))

或者用更简洁的apply写法:

df = df.apply(lambda col: pd.to_numeric(col.str.replace(',', '')) if col.dtype == 'object' else col)

注意点

  • 若数据中存在空值或非数值字符串,可在pd.to_numeric中添加errors='coerce'参数,将无法转换的值转为NaN,避免报错:
df[col] = pd.to_numeric(df[col].str.replace(',', ''), errors='coerce')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:05:33