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


当前回答

如果只是在pandas列中计算nan值,这里是一个快速的方法

import pandas as pd
## df1 as an example data frame 
## col1 name of column for which you want to calculate the nan values
sum(pd.isnull(df1['col1']))

其他回答

让我们假设df是一个熊猫数据框架。

然后,

df.isnull().sum(axis = 0)

这将给出每列中NaN值的数量。

如果你需要,每一行的NaN值,

df.isnull().sum(axis = 1)

如果你正在使用Jupyter笔记本,如何....

 %%timeit
 df.isnull().any().any()

or

 %timeit 
 df.isnull().values.sum()

或者,数据中是否存在nan,如果有,在哪里?

 df.isnull().any()

你可以使用value_counts方法打印np.nan的值

s.value_counts(dropna = False)[np.nan]

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

假设您希望获得一个名为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