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


当前回答

df1.isnull().sum()

这样就可以了。

其他回答

import pandas as pd
import numpy as np

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

# count the NaNs in a column
num_nan_a = df.loc[ (pd.isna(df['a'])) , 'a' ].shape[0]
num_nan_b = df.loc[ (pd.isna(df['b'])) , 'b' ].shape[0]

# summarize the num_nan_b
print(df)
print(' ')
print(f"There are {num_nan_a} NaNs in column a")
print(f"There are {num_nan_b} NaNs in column b")

给出输出:

     a    b
0  1.0  NaN
1  2.0  1.0
2  NaN  NaN

There are 1 NaNs in column a
There are 2 NaNs in column b

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

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

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

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

假设您希望获得一个名为reviews的数据框架中称为price的列(系列)中缺失值(NaN)的数量

#import the dataframe
import pandas as pd

reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)

用n_missing_prices作为变量来获取缺失的值,简单地做

n_missing_prices = sum(reviews.price.isnull())
print(n_missing_prices)

Sum是这里的关键方法,在我意识到Sum是在这种情况下使用的正确方法之前,我试图使用count

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

数零:

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

计算NaN:

df.isnull().sum()

or

df.isna().sum()