【Pandas】pandas Series notnull

# Pandas2.2 Series

## Computations descriptive stats

|方法|描述|

|-|:-------|

|Series.backfill(*[, axis, inplace, limit, ...])|用于填充 `Series` 中缺失值(NaN)的方法|

|Series.bfill(*[, axis, inplace, limit, ...])|用于填充 `Series` 中缺失值(NaN)的方法|

|Series.dropna(*[, axis, inplace, how, ...])|用于删除 `Series` 中包含缺失值(NaN)的元素的方法|

|Series.ffill(*[, axis, inplace, limit, ...])|用于填充 `Series` 中缺失值(NaN)的方法|

|Series.fillna([value, method, axis, ...])|用于填充 `Series` 中缺失值(NaN)的方法|

|Series.interpolate([method, axis, limit, ...])|用于填充 `Series` 中缺失值(NaN)的方法|

|Series.isna()|用于检测 `Series` 中的缺失值(NaN)的方法|

|Series.isnull()|用于检测 `Series` 中的缺失值(NaN)的方法|

|Series.notna()|用于检测 `Series` 中的非缺失值(即不是 NaN 或 None)的方法|

|Series.notnull()|用于检测 `Series` 中的非缺失值(即不是 NaN 或 None)的方法|

### pandas.Series.notnull

`pandas.Series.notnull()` 是用于检测 `Series` 中的非缺失值(即不是 NaN 或 None)的方法。它会返回一个布尔型的 `Series`,其中每个元素表示对应位置是否为非缺失值。`notnull()` 方法与 `notna()` 方法功能相同,二者可以互换使用。

#### 参数说明

- 无参数。

#### 返回值

- **Series**:布尔型的 `Series`,与原 `Series` 长度相同,值为 `True` 表示该位置不是缺失值,值为 `False` 表示该位置是缺失值。

#### 示例及结果

##### 示例1:基本用法

```python

import pandas as pd

import numpy as np

# 创建一个包含缺失值的 Series

s = pd.Series([1, np.nan, 'hello', None, 5])

print("原始 Series:")

print(s)

# 使用 notnull 方法检测非缺失值

not_null_s = s.notnull()

print("\n检测非缺失值后的 Series (使用 notnull):")

print(not_null_s)

```

**输出结果:**

```plaintext

原始 Series:

0        1

1      NaN

2    hello

3     None

4        5

dtype: object

检测非缺失值后的 Series (使用 notnull):

0     True

1    False

2     True

3    False

4     True

dtype: bool

```

##### 示例2:结合布尔索引筛选非缺失值

```python

# 使用 notnull 方法结合布尔索引筛选非缺失值

non_missing_values = s[s.notnull()]

print("\n筛选出的非缺失值:")

print(non_missing_values)

```

**输出结果:**

```plaintext

筛选出的非缺失值:

0        1

2    hello

4        5

dtype: object

```

##### 示例3:比较 `notnull` 和 `notna`

```python

# 比较 notnull 和 notna 的结果

not_na_s = s.notna()

print("\n使用 notna 方法检测非缺失值:")

print(not_na_s)

print("\n使用 notnull 方法检测非缺失值:")

print(not_null_s)

# 检查两个方法的结果是否一致

print("\nnotnull 和 notna 的结果是否一致:", not_na_s.equals(not_null_s))

```

**输出结果:**

```plaintext

使用 notna 方法检测非缺失值:

0     True

1    False

2     True

3    False

4     True

dtype: bool

使用 notnull 方法检测非缺失值:

0     True

1    False

2     True

3    False

4     True

dtype: bool

notnull 和 notna 的结果是否一致: True

```

通过这些示例,可以看到 `notnull` 方法能够有效地检测 `Series` 中的非缺失值,并返回布尔型的结果,便于进一步的数据处理和分析。`notnull` 和 `notna` 方法在功能上完全相同,可以根据个人习惯选择使用。

#### 总结

- `notnull()` 和 `notna()` 方法用于检测 `Series` 中的非缺失值。

- 返回值是一个布尔型的 `Series`,`True` 表示非缺失值,`False` 表示缺失值。

- 可以结合布尔索引进行数据筛选,提取非缺失值部分。

#### 应用场景

- **数据清洗**:在数据预处理阶段,可以使用 `notnull()` 或 `notna()` 来识别并处理缺失值。

- **数据过滤**:结合布尔索引,可以轻松地从 `Series` 或 `DataFrame` 中筛选出非缺失值,以便进一步分析或建模。

- **数据验证**:确保数据集中没有意外的缺失值,特别是在关键字段中。

这两种方法在处理缺失值时非常有用,能够帮助用户更高效地管理和分析数据。