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


当前回答

你可以试试:

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] 

其他回答

自从pandas 0.14.1以来,我的建议在value_counts方法中有一个关键字参数已经实现:

import pandas as pd
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
for col in df:
    print df[col].value_counts(dropna=False)

2     1
 1     1
NaN    1
dtype: int64
NaN    2
 1     1
dtype: int64
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

下面是按列计数Null值的代码:

df.isna().sum()

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

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

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

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

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

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

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

or

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

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