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

如何在pandas.to_numeric()中将int64转换为int32?

解决方法

问题出在pd.to_numeric(x, downcast="integer")的逻辑上:这个参数会根据数据的实际取值范围自动选择最小的适配整数类型,如果你的数据值都落在int8的区间(-128到127)内,就会自动转成int8,而非你想要的int32。

要强制转换为int32,有两种可靠方式:

方法一:直接用astype()指定类型

这是最直接的方式,只要数据值在int32的范围内(-2147483648 到 2147483647),就能直接完成转换:

# 假设你的DataFrame是df,目标列是target_col
df['target_col'] = df['target_col'].astype('int32')

方法二:先校验范围再转换(更安全)

如果不确定数据是否超出int32的取值范围,可以先做校验,避免转换报错:

min_val = df['target_col'].min()
max_val = df['target_col'].max()
# int32的取值范围是 -2^31 到 2^31 -1
if min_val >= -2**31 and max_val <= 2**31 - 1:
    df['target_col'] = df['target_col'].astype('int32')
else:
    print("数据超出int32的取值范围,无法完成转换")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 06:45:28