我想找出我的数据的每一列中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()

根据给出的答案和一些改进,这是我的方法

def PercentageMissin(Dataset):
    """this function will return the percentage of missing values in a dataset """
    if isinstance(Dataset,pd.DataFrame):
        adict={} #a dictionary conatin keys columns names and values percentage of missin value in the columns
        for col in Dataset.columns:
            adict[col]=(np.count_nonzero(Dataset[col].isnull())*100)/len(Dataset[col])
        return pd.DataFrame(adict,index=['% of missing'],columns=adict.keys())
    else:
        raise TypeError("can only be used with panda dataframe")

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

如果你需要得到非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)