【Pandas】pandas Series isnull

# 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)的方法|

### pandas.Series.notna

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

#### 参数说明

- 无参数。

#### 返回值

- **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)

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

not_na_s = s.notna()

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

print(not_na_s)

```

**输出结果:**

```plaintext

原始 Series:

0        1

1      NaN

2    hello

3     None

4        5

dtype: object

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

0     True

1    False

2     True

3    False

4     True

dtype: bool

```

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

```python

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

non_missing_values = s[s.notna()]

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

print(non_missing_values)

```

**输出结果:**

```plaintext

筛选出的非缺失值:

0        1

2    hello

4        5

dtype: object

```

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

```python

# 比较 notna 和 notnull 的结果

not_null_s = s.notnull()

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

print(not_null_s)

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

print(not_na_s)

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

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

```

**输出结果:**

```plaintext

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

0     True

1    False

2     True

3    False

4     True

dtype: bool

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

0     True

1    False

2     True

3    False

4     True

dtype: bool

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

```

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

#### 总结

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

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

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