# 如何计算 Pandas Dataframe 列中的 NaN 出现的次数

## `isna()` 方法来计算一列或多列中的 NaN

``````import pandas as pd

s = pd.Series([1, 2, 3, np.nan, np.nan])
s.isna().sum()
# or s.isnull().sum() for older pandas versions
``````

``````2
``````

``````import pandas as pd

df = pd.DataFrame({"a": [1, 2, np.nan], "b": [np.nan, 1, np.nan]})
df.isna().sum()
``````

``````a    1
b    2
dtype: int64
``````

## 从总长度中减去 `non-NaN` 的计数以计算 `NaN` 的出现次数

``````import pandas as pd

df = pd.DataFrame(
[(1, 2, None), (None, 4, None), (5, None, 7), (5, None, None)],
columns=["a", "b", "d"],
index=["A", "B", "C", "D"],
)
print(df)
print(len(df) - df.count())
``````

``````     a    b    d
A  1.0  2.0  NaN
B  NaN  4.0  NaN
C  5.0  NaN  7.0
D  5.0  NaN  NaN
a    1
b    2
d    3
dtype: int64
``````

## `df.isnull().sum()` 方法来计算 `NaN` 的出现次数

``````import pandas as pd

df = pd.DataFrame(
[(1, 2, None), (None, 4, None), (5, None, 7), (5, None, None)],
columns=["a", "b", "d"],
index=["A", "B", "C", "D"],
)

print("NaN occurrences in Columns:")
print(df.isnull().sum(axis=0))
print("NaN occurrences in Rows:")
print(df.isnull().sum(axis=1))
``````

``````NaN occurrences in Columns:
a    1
b    2
d    3
dtype: int64
NaN occurrences in Rows:
A    1
B    2
C    1
D    2
dtype: int64
``````

## 计算整个 Pandas DataFrame 中 `NaN` 的出现

``````import pandas as pd

df = pd.DataFrame(
[(1, 2, None), (None, 4, None), (5, None, 7), (5, None, None)],
columns=["a", "b", "d"],
index=["A", "B", "C", "D"],
)

print("NaN occurrences in DataFrame:")
print(df.isnull().sum().sum())
``````

``````NaN occurrences in DataFrame:
6
``````