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

Asad Riaz 2023年1月30日 2020年3月28日 Pandas Pandas DataFrame

## `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
``````

## 相关文章 - Pandas DataFrame

• 如何将 Pandas DataFrame 列标题获取为列表
• 如何删除 Pandas DataFrame 列
• 如何在 Pandas 中将 DataFrame 列转换为日期时间
• 如何在 Pandas DataFrame 中将浮点数转换为整数
• 如何按一列的值对 Pandas DataFrame 进行排序
• 如何用 group-by 和 sum 获得 Pandas 总和