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


当前回答

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

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")

其他回答

可以使用df.iteritems()对数据帧进行循环。在for循环中设置一个条件来计算每列的NaN值百分比,并删除那些包含NaN值超过设置阈值的值:

for col, val in df.iteritems():
    if (df[col].isnull().sum() / len(val) * 100) > 30:
        df.drop(columns=col, inplace=True)

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

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

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

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

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

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

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

or

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

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

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