我想找出我的数据的每一列中NaN的数量。
当前回答
我使用这个循环来计算每一列的缺失值:
# check missing values
import numpy as np, pandas as pd
for col in df:
print(col +': '+ np.str(df[col].isna().sum()))
其他回答
下面的代码将按降序打印所有Nan列。
df.isnull().sum().sort_values(ascending = False)
or
下面将按降序打印前15个Nan列。
df.isnull().sum().sort_values(ascending = False).head(15)
如果你正在使用Jupyter笔记本,如何....
%%timeit
df.isnull().any().any()
or
%timeit
df.isnull().values.sum()
或者,数据中是否存在nan,如果有,在哪里?
df.isnull().any()
我写了一个简短的函数(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。
方法1计数,由于计数将忽略与大小不同的NaN
print(len(df) - df.count())
方法2:isnull / isna chain with sum
print(df.isnull().sum())
#print(df.isna().sum())
方法3 describe / info:注意这将输出' notull '值计数
print(df.describe())
#print(df.info())
方法。
print(np.count_nonzero(np.isnan(df.values),axis=0))
对于问题的第二部分,如果我们想要在thresh中删除列,我们可以尝试dropna
thresh, optional要求多个非na值。
Thresh = n # no null value require, you can also get the by int(x% * len(df))
df = df.dropna(thresh = Thresh, axis = 1)
df1.isnull().sum()
这样就可以了。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 确定每列中NA值的个数
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 如何结合多个条件子集数据帧使用“或”?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式