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

如何去除Pandas DataFrame列中的逗号并转换为整数类型

解决印度各邦人口数据类型转换问题

问题原因

你遇到的NaN问题根源在于2011和2023列是object类型,列内混合了带逗号的字符串与纯数值两种数据。调用str.replace时,仅字符串类型元素能被正常处理,数值类型元素会直接转为NaN。

解决方案

方案1:统一转字符串后替换并转整数

先将列内所有元素强制转为字符串,去除逗号后再转换为整数类型。如果数据无真实空值,直接用int即可:

import pandas as pd
import numpy as np

# 读取数据
df = pd.read_excel("https://github.com/gambler2020/Data/blob/main/indian%20state%20population.xlsx?raw=true")

# 处理2011列
df['2011'] = df['2011'].astype(str).str.replace(',', '').astype(int)
# 处理2023列
df['2023'] = df['2023'].astype(str).str.replace(',', '').astype(int)

# 查看处理后的列类型
print(df.dtypes)

方案2:稳健处理异常值

如果数据中可能存在无法转换的异常值,使用pd.to_numeric配合errors='coerce'将异常值转为NaN,再用可空整数类型Int64保留空值信息:

df['2011'] = pd.to_numeric(df['2011'].astype(str).str.replace(',', ''), errors='coerce').astype('Int64')
df['2023'] = pd.to_numeric(df['2023'].astype(str).str.replace(',', ''), errors='coerce').astype('Int64')

验证结果

处理后执行df.head(10),所有数值将正常保留且类型转为整数,不会再出现NaN:

States          2011        2023
0   Uttar Pradesh   199812341   235687000
1   Maharashtra     112374333   126385000
2   Bihar           104099452   126756000
3   West Bengal     91276115    99084000
4   Madhya Pradesh  72626809    86579000
5   Tamil Nadu      72147030    ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:27:47