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


当前回答

可以使用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)

其他回答

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

df.isna().sum()

你可以从非nan值的计数中减去总长度:

count_nan = len(df) - df.count()

你应该根据你的数据计算时间。与isnull解相比,小级数的速度提高了3倍。

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
df.isnull().sum() 
      //type: <class 'pandas.core.series.Series'>

or

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

.sum df.isnull () () 将给出缺失值的列和。

如果你想知道特定列中缺失值的总和,那么以下代码将起作用: