如何在 Pandas 中检查 NaN 值

2024 年 8 月 29 日 | 5 分钟阅读

在 Pandas 的原始文档中,空值被描述为缺失值。正如大多数程序员所做的那样,我们可以将 Pandas 中的空值或缺失数据指定为 NaN。

NaN,意思是“非数字”(Not A Number),是表示数据集中值缺失的常用方法之一。它是一种特殊的浮点数对象,只能转换为浮点数数据类型。

NaN 值是数据处理中的主要问题之一。如果你想实现你的目标,处理 NaN 是至关重要的。

程序员可以使用 NaN 或 None Python 关键字来显示 DataFrame 中的空条目。Pandas 将 NaN 和 None 同等处理是其最吸引人的特性。如果单元格包含 NaN 或 None,pandas.notnull 将返回 False 来确定组件是否缺失。我们也可以使用 .isnull(),它与 .notnull 函数相反;因此,如果值是空值或 NaN,它将返回 True。

因此,在本教程中,我们将研究几种技术,以确定特定单元格、系列或整个 DataFrame 是否包含空值(NaN 或 None)。

我们将讨论的几种方法包括:

  1. isnull
  2. isnan
  3. isna
  4. notnull

使用 .isnull 函数

我们可以使用此函数检查哪些单元格包含空值。下面是一个示例。

代码

输出

    numbers
0     False
1     False
2     False
3     False
4     False
5     False
6      True
7     False
8     False
9      True
10    False
11    False
12    False
13     True

此外,使用 isnull.values.any(),我们可以检查数据帧的系列是否包含任何空值。它将为我们提供布尔结果。

代码

输出

True

使用相同的 isnull() 函数,我们还可以获得数据帧系列中存在的空值的总数。

代码

输出

The sum of NaN entries present in a series: 3

您可以使用以下代码计算整个 DataFrame 中的 NaN 值。

代码

输出

The sum of Nan values in the data frame: 8

使用 isnan() 方法

在上一个示例中,我们使用 pandas.isnull 函数验证了 NaN 条目。我们现在将采用一种称为 isnan 的不同技术。此函数是 numpy 库的内置函数。下面的代码展示了如何检查特定单元格中的 NaN 值。

代码

输出

The particular value of the data frame is nan: True

在前面的示例中,我们查找了 DataFrame 单元格中的 NaN 对象。此外,我们可以确定 Pandas 系列中的单元格值是否为 NaN。让我们看看如何将其付诸实践。

代码

输出

The value at series[3] is NaN: False

使用 Pandas 的 .isna 函数

我们将展示如何使用 Pandas 的 .isna 函数。

代码

输出

checking for NaN value in the series numbers2 at the 6th index
True

使用 .notnull 方法

notnull 函数是确定单元格是否为 NaN 或 DataFrame 是否包含空值的另一种方法。根据下面的程序,如果给定的单元格值是 NaN 或空值,此函数将返回布尔结果 False。

代码

输出

The cell does not has a null value:  False
The series does has not null value:  True
Number of no null value in the series of the dataframe:  numbers1    12
numbers2    10
dtype: int64