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


当前回答

自从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

其他回答

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观测值的个数

在我的代码中使用@sushmit提出的解决方案。

同样的一种可能的变体也可以是

colNullCnt = []
for z in range(len(df1.cols)):
    colNullCnt.append([df1.cols[z], sum(pd.isnull(trainPd[df1.cols[z]]))])

这样做的好处是,它将返回df中每一列的结果。

另一个尚未被建议的简单选项是,为了只计算NaN,将在形状中添加以返回具有NaN的行数。

df[df['col_name'].isnull()]['col_name'].shape

数零:

df[df == 0].count(axis=0)

计算NaN:

df.isnull().sum()

or

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和总条目数。