我想找出我的数据的每一列中NaN的数量。


当前回答

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.count.html#pandas.Series.count

pandas.Series.count
Series.count(level=None)[source]

返回系列中非na /null观测值的个数

其他回答

import pandas as pd
import numpy as np

# example DataFrame
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})

# count the NaNs in a column
num_nan_a = df.loc[ (pd.isna(df['a'])) , 'a' ].shape[0]
num_nan_b = df.loc[ (pd.isna(df['b'])) , 'b' ].shape[0]

# summarize the num_nan_b
print(df)
print(' ')
print(f"There are {num_nan_a} NaNs in column a")
print(f"There are {num_nan_b} NaNs in column b")

给出输出:

     a    b
0  1.0  NaN
1  2.0  1.0
2  NaN  NaN

There are 1 NaNs in column a
There are 2 NaNs in column b

让我们假设df是一个熊猫数据框架。

然后,

df.isnull().sum(axis = 0)

这将给出每列中NaN值的数量。

如果你需要,每一行的NaN值,

df.isnull().sum(axis = 1)

下面的代码将按降序打印所有Nan列。

df.isnull().sum().sort_values(ascending = False)

or

下面将按降序打印前15个Nan列。

df.isnull().sum().sort_values(ascending = False).head(15)

如果你需要得到非NA (non-None)和NA (None)计数在不同的组拉出groupby:

gdf = df.groupby(['ColumnToGroupBy'])

def countna(x):
    return (x.isna()).sum()

gdf.agg(['count', countna, 'size'])

这将返回每个组的非NA、NA和总条目数。

你可以试试:

In [1]: s = pd.DataFrame('a'=[1,2,5, np.nan, np.nan,3],'b'=[1,3, np.nan, np.nan,3,np.nan])

In [4]: s.isna().sum()   
Out[4]: out = {'a'=2, 'b'=3} # the number of NaN values for each column

如果需要nan的总和:

In [5]: s.isna().sum().sum()
Out[6]: out = 5  #the inline sum of Out[4]