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


当前回答

对于第一部分,我们有多种方法计算NaN。

方法1计数,由于计数将忽略与大小不同的NaN

print(len(df) - df.count())

方法2:isnull / isna chain with sum

print(df.isnull().sum())
#print(df.isna().sum())

方法3 describe / info:注意这将输出' notull '值计数

print(df.describe())
#print(df.info())

方法。

print(np.count_nonzero(np.isnan(df.values),axis=0))

对于问题的第二部分,如果我们想要在thresh中删除列,我们可以尝试dropna

thresh, optional要求多个非na值。

Thresh = n # no null value require, you can also get the by int(x% * len(df))
df = df.dropna(thresh = Thresh, axis = 1)

其他回答

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

df.isna().sum()

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

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

这样就可以了。

2017年7月,Dzone有一篇不错的文章,详细介绍了总结NaN值的各种方法。点击这里查看。

我所引用的文章提供了额外的价值:(1)展示了一种方法来计算和显示每列的NaN计数,以便人们可以轻松地决定是否丢弃这些列;(2)演示了一种方法来选择那些特定的具有NaN的行,以便它们可以选择性地丢弃或估算。

这里有一个快速的例子来演示这种方法的实用性——只有几个列,也许它的有用性不明显,但我发现它对较大的数据框架很有帮助。

import pandas as pd
import numpy as np

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

# Check whether there are null values in columns
null_columns = df.columns[df.isnull().any()]
print(df[null_columns].isnull().sum())

# One can follow along further per the cited article

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