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

pandas使用to_numeric得到int32 如何转换为int64类型

pandas to_numeric转换类型问题解答

疑问1:为什么to_numeric转换后得到int32而非默认int64

你观察到的int32类型并非pd.to_numeric的默认返回结果,问题出在链式调用的astype(int)步骤:

  • pd.to_numeric默认确实会返回int64或float64类型,和官方文档描述一致
  • Python原生的int在部分运行环境(比如32位Python、默认配置的Windows系统)下,对应numpy的int32类型,你调用astype(int)时覆盖了to_numeric的默认类型输出
  • 额外提示:你代码末尾的to_frame()属于冗余操作,给DataFrame单列赋值时传入Series即可,to_frame()会将结果转为单栏DataFrame,可能引入非预期的赋值问题。

疑问2:如何将int32转为int64、解决长数值溢出为负数的问题

你只需要修改astype的参数,明确指定转换为int64类型即可,修改后的代码如下:

import pandas as pd

df['MPRN'] = pd.to_numeric(df['MPRN'], errors="coerce").fillna(0).astype('int64')

修改后再调用df.info()查看,即可看到MPRN列的类型已经变为int64,超过10位的长数值也不会出现溢出变负数的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:24:02