我想找出我的数据的每一列中NaN的数量。
当前回答
你可以使用value_counts方法打印np.nan的值
s.value_counts(dropna = False)[np.nan]
其他回答
让我们假设df是一个熊猫数据框架。
然后,
df.isnull().sum(axis = 0)
这将给出每列中NaN值的数量。
如果你需要,每一行的NaN值,
df.isnull().sum(axis = 1)
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
你可以试试:
In [1]: s = pd.DataFrame('a'=[1,2,5, np.nan, np.nan,3],'b'=[1,3, np.nan, np.nan,3,np.nan])
In [4]: s.isna().sum()
Out[4]: out = {'a'=2, 'b'=3} # the number of NaN values for each column
如果需要nan的总和:
In [5]: s.isna().sum().sum()
Out[6]: out = 5 #the inline sum of Out[4]
.sum df.isnull () () 将给出缺失值的列和。
如果你想知道特定列中缺失值的总和,那么以下代码将起作用:
另一个尚未被建议的简单选项是,为了只计算NaN,将在形状中添加以返回具有NaN的行数。
df[df['col_name'].isnull()]['col_name'].shape