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

如何在pandas DataFrame中仅定位NaN值而非None值

实现仅查找DataFrame中NaN值的方案

首先明确pandas中两类空值的差异:NaN属于numpy的float类型缺失值,None是Python原生空对象,df.isnull()会将两类值统一判定为True,要单独筛选NaN可以按以下方法实现:

方法1:全表逐元素判断

直接对每个元素做双重判定,同时排除None的干扰,适合中小体量DataFrame使用:

import numpy as np
import pandas as pd

# 生成布尔掩码,仅NaN位置为True
nan_mask = df.applymap(lambda x: isinstance(x, float) and np.isnan(x))

方法2:分列优化处理

数据量较大时可按列类型分别处理,提升运行效率:

  • float类型列中pandas会自动将None转为NaN,不存在原生None,可直接用np.isnan()判断
  • object类型列可同时存储None和NaN,需要做双重判定
nan_mask = pd.DataFrame(False, index=df.index, columns=df.columns)

# 处理所有float列
float_cols = df.select_dtypes(include='float').columns
nan_mask[float_cols] = np.isnan(df[float_cols])

# 处理所有object列
object_cols = df.select_dtypes(include='object').columns
nan_mask[object_cols] = df[object_cols].applymap(lambda x: isinstance(x, float) and np.isnan(x))

常用后续操作

  • 获取所有NaN的坐标位置(行索引、列名对应):
nan_positions = [(df.index[i], df.columns[j]) for i,j in zip(*np.where(nan_mask))]
  • 筛选包含NaN的行:
rows_with_nan = df[nan_mask.any(axis=1)]

注意:如果你的DataFrame中存在Nullable整数类型(如Int64)、Nullable布尔类型(如boolean),这些类型的缺失值会显示为<NA>,不属于NaN,上述方法不会将其判定为匹配结果,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 00:27:03