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


当前回答

df.isnull().sum() 
      //type: <class 'pandas.core.series.Series'>

or

df.column_name.isnull().sum()
     //type: <type 'numpy.int64'>

其他回答

对于你的任务,你可以使用pandas.DataFrame.dropna (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html):

import pandas as pd
import numpy as np

df = pd.DataFrame({'a': [1, 2, 3, 4, np.nan],
                   'b': [1, 2, np.nan, 4, np.nan],
                   'c': [np.nan, 2, np.nan, 4, np.nan]})
df = df.dropna(axis='columns', thresh=3)

print(df)

使用thresh参数,您可以声明DataFrame中所有列的NaN值的最大计数。

代码输出:

     a    b
0  1.0  1.0
1  2.0  2.0
2  3.0  NaN
3  4.0  4.0
4  NaN  NaN

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

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

下面是按列计数Null值的代码:

df.isna().sum()

如果只是在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']))
df1.isnull().sum()

这样就可以了。