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


当前回答

希望这能有所帮助,

import pandas as pd
import numpy as np
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan],'c':[np.nan,2,np.nan], 'd':[np.nan,np.nan,np.nan]})

df.isnull().sum()/len(df) * 100

Thres = 40
(df.isnull().sum()/len(df) * 100 ) < Thres

其他回答

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

让我们假设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)

数零:

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

计算NaN:

df.isnull().sum()

or

df.isna().sum()

对于第一部分,我们有多种方法计算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)