You need to enable JavaScript to run this app. 为何pd.isnull(data).any()与any(df.isnull())检测缺失值结果不同?
优惠活动
大模型
产品
解决方案
定价
更多

为何pd.isnull(data).any()与any(df.isnull())检测缺失值结果不同?

波士顿房价数据集缺失值检测结果不一致的原因

问题重现

加载数据集的代码:

# loading df
from sklearn.datasets import load_boston
boston=load_boston()
boston_data = pd.DataFrame(data=boston.data, columns=boston.feature_names)
boston_data['price']=boston.target # the price column

两种检测方式的结果:

  1. 执行pd.isnull(boston_data).any(),返回所有列均无缺失值:
CRIM       False
ZN         False
INDUS      False
CHAS       False
NOX        False
RM         False
AGE        False
DIS        False
RAD        False
TAX        False
PTRATIO    False
B          False
LSTAT      False
price      False
dtype: bool
  1. 执行any(boston_data.isnull()),返回True。

原因分析

这两个写法本质是在执行完全不同的操作:

  • pd.isnull(boston_data).any():调用的是pandas DataFrame自带的any()方法,默认参数axis=0,会逐列检查该列是否存在至少一个缺失值(即True),返回的是每列的检查结果。你的结果显示所有列都没有缺失值,因此全为False。
  • any(boston_data.isnull()):调用的是Python内置的any()函数。pandas DataFrame默认的迭代逻辑是遍历列名(字符串类型的列标签),而任何非空字符串在布尔判断中都会被视为True。由于数据集包含多个非空列名,any()函数只要遇到第一个True就会返回结果,最终得到True。

正确的全局缺失值检测方式

如果想用Python内置函数检查整个数据集是否存在缺失值,需要先将布尔DataFlatten为一维数组:

any(boston_data.isnull().values.flatten())

或者直接使用pandas的方法:

pd.isnull(boston_data).any().any()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:02:51