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

为何Pandas中新增未匹配索引的Series数据类型从int转为float?

问题

我在练习Pandas时编写了以下代码:

data_dict={'Ahmed':90,'Ali':85,'Omar':80}
series=pd.Series(data_dict,index=['Ahmed','Ali','Omar'])
print("Series :",series)
series2=pd.Series(data_dict,index=['Ahmed','Ali','Omar','Karthi'])
print("Series 2 :",series2)

得到的输出如下:

Series :
Ahmed    90
Ali      85
Omar     80
dtype: int64

Series 2 :
Ahmed     90.0
Ali       85.0
Omar      80.0
Karthi     NaN
dtype: float64

我在索引中添加了字典中不存在的字段Karthi,结果得到NaN值,但Series 2的数据类型从int64变为float64,请问这是什么原因?

回答

核心原因:NaN的类型限制

Pandas里的缺失值NaN本质是浮点类型(对应numpy.float64),而普通的整数类型(比如int64)没办法存储缺失值——整数体系里没有专门表示"缺失"的合法值。

当你给series2添加了字典中不存在的索引Karthi时,Pandas会自动为这个位置填充NaN。为了让Series既能保存原来的整数值,又能容纳新增的NaN,Pandas会触发类型提升机制,把整个Series的数据类型从int64转为float64,这样所有元素都能被正确存储。

可选解决方案:保留整数类型处理缺失值

如果需要在保留整数类型的同时支持缺失值,可以使用Pandas提供的可空整数类型Int64(注意首字母大写),示例代码如下:

series2 = pd.Series(data_dict, index=['Ahmed','Ali','Omar','Karthi'], dtype='Int64')

此时输出的dtype为Int64,Karthi对应的缺失值会显示为<NA>,而非NaN。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:51:57