我想找出我的数据的每一列中NaN的数量。
当前回答
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[df == 0].count(axis=0)
计算NaN:
df.isnull().sum()
or
df.isna().sum()
如果你正在使用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
2017年7月,Dzone有一篇不错的文章,详细介绍了总结NaN值的各种方法。点击这里查看。
我所引用的文章提供了额外的价值:(1)展示了一种方法来计算和显示每列的NaN计数,以便人们可以轻松地决定是否丢弃这些列;(2)演示了一种方法来选择那些特定的具有NaN的行,以便它们可以选择性地丢弃或估算。
这里有一个快速的例子来演示这种方法的实用性——只有几个列,也许它的有用性不明显,但我发现它对较大的数据框架很有帮助。
import pandas as pd
import numpy as np
# example DataFrame
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
# Check whether there are null values in columns
null_columns = df.columns[df.isnull().any()]
print(df[null_columns].isnull().sum())
# One can follow along further per the cited article
你可以从非nan值的计数中减去总长度:
count_nan = len(df) - df.count()
你应该根据你的数据计算时间。与isnull解相比,小级数的速度提高了3倍。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获取迭代器中的元素个数
- 解析日期字符串并更改格式