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


当前回答

数零:

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

计算NaN:

df.isnull().sum()

or

df.isna().sum()

其他回答

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

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

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

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

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

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

希望这能有所帮助,

import pandas as pd
import numpy as np
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan],'c':[np.nan,2,np.nan], 'd':[np.nan,np.nan,np.nan]})

df.isnull().sum()/len(df) * 100

Thres = 40
(df.isnull().sum()/len(df) * 100 ) < Thres

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

如果你需要得到非NA (non-None)和NA (None)计数在不同的组拉出groupby:

gdf = df.groupby(['ColumnToGroupBy'])

def countna(x):
    return (x.isna()).sum()

gdf.agg(['count', countna, 'size'])

这将返回每个组的非NA、NA和总条目数。