我想找出我的数据的每一列中NaN的数量。
当前回答
如果你需要得到非NA (non-None)和NA (None)计数在不同的组拉出groupby:
gdf = df.groupby(['ColumnToGroupBy'])
def countna(x):
return (x.isna()).sum()
gdf.agg(['count', countna, 'size'])
这将返回每个组的非NA、NA和总条目数。
其他回答
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
下面的代码将按降序打印所有Nan列。
df.isnull().sum().sort_values(ascending = False)
or
下面将按降序打印前15个Nan列。
df.isnull().sum().sort_values(ascending = False).head(15)
我写了一个简短的函数(Python 3)来生成.info作为pandas数据框架,然后可以写入excel:
df1 = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
def info_as_df (df):
null_counts = df.isna().sum()
info_df = pd.DataFrame(list(zip(null_counts.index,null_counts.values))\
, columns = ['Column', 'Nulls_Count'])
data_types = df.dtypes
info_df['Dtype'] = data_types.values
return info_df
print(df1.info())
print(info_as_df(df1))
这使:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 a 2 non-null float64
1 b 1 non-null float64
dtypes: float64(2)
memory usage: 176.0 bytes
None
Column Nulls_Count Dtype
0 a 1 float64
1 b 2 float64
另一个尚未被建议的简单选项是,为了只计算NaN,将在形状中添加以返回具有NaN的行数。
df[df['col_name'].isnull()]['col_name'].shape
使用isna()方法(或者它的别名isnull(),这也兼容较旧的pandas版本< 0.21.0),然后求和来计算NaN值。其中一列:
>>> s = pd.Series([1,2,3, np.nan, np.nan])
>>> s.isna().sum() # or s.isnull().sum() for older pandas versions
2
对于一些列,这也适用:
>>> df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
>>> df.isna().sum()
a 1
b 2
dtype: int64