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

含NaN的Pandas数据赋值异常:为何5.0未转为整数5?

问题分析与解决

核心原因

  1. 缺少依赖导入:你的代码未导入math模块,运行时会触发NameError,这是基础错误。
  2. Pandas dtype 限制:Pandas常规整数类型(int64)无法兼容NaN,因为NaN属于浮点类型。当列中存在NaN时,整列会被强制转为float64类型——哪怕你把5.0转成整数5,Pandas也会自动将其转回5.0,以保证列内类型统一。

解决方案

要同时保留整数和NaN,需使用Pandas的可空整数类型Int64(首字母大写),它专门设计用来兼容整数与缺失值。

修改后的完整代码

import pandas as pd
import numpy as np
import math  # 补充导入math模块

df = pd.DataFrame({"A":[5.0,np.nan], "B":[2.0,3.0]})

def casting(x):
    if math.isnan(x):
        return pd.NA  # 使用pd.NA适配可空整数类型
    else:
        return int(x)

# 转换后指定Int64 dtype
df['A'] = df['A'].map(casting).astype('Int64')
print(df)

简化写法(无需自定义函数)

用np.where直接实现,代码更简洁:

import pandas as pd
import numpy as np

df = pd.DataFrame({"A":[5.0,np.nan], "B":[2.0,3.0]})

df['A'] = np.where(df['A'].notna(), df['A'].astype(int), df['A']).astype('Int64')
print(df)

最终输出

A    B
0    5  2.0
1  NaN  3.0

此时列A的 dtype 为Int64,既能存储整数5,也能正常保留缺失值NaN。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:07:15