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

Pandas 1.0+版本中带缺失值的浮点Series如何转换为整数类型?

搞定Pandas含缺失值的Series类型转换

平时咱们把Pandas Series转成整数类型超简单,一行代码就搞定:

s = pd.Series([1.1, 2.2]).astype(int)

直接把浮点数截断成整数,完全没毛病。

但要是你的Series里带了pd.NA这种缺失值,再用astype(int)就会踩坑了:

s = pd.Series([1.1, 2.2, pd.NA]).astype(int)

这时候会直接抛出TypeError: int() argument must be a string, a bytes-like object or a number, not 'NAType'——原因很简单,原生的int类型根本不认识Pandas的NAType缺失值。

不过Pandas早就想到这个问题了,它提供了可空整数类型来解决这个场景,你只需要把转换目标换成pd.Int64Dtype()(注意这里是首字母大写的Int64,和原生int区分开)就行:

s = pd.Series([1, 2, pd.NA]).astype(pd.Int64Dtype())

这样就能在整数类型的Series里正常存缺失值,再也不会报错啦。

顺带提一句,就算是带缺失值的浮点数Series,也能用这个方法转成可空整数类型:

s = pd.Series([1.1, 2.2, pd.NA]).astype(pd.Int64Dtype())

它会自动把浮点数截断为整数,同时保留pd.NA缺失值,完美适配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 08:47:43