我想找出我的数据的每一列中NaN的数量。
当前回答
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
其他回答
假设您希望获得一个名为reviews的数据框架中称为price的列(系列)中缺失值(NaN)的数量
#import the dataframe
import pandas as pd
reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)
用n_missing_prices作为变量来获取缺失的值,简单地做
n_missing_prices = sum(reviews.price.isnull())
print(n_missing_prices)
Sum是这里的关键方法,在我意识到Sum是在这种情况下使用的正确方法之前,我试图使用count
另一个尚未被建议的简单选项是,为了只计算NaN,将在形状中添加以返回具有NaN的行数。
df[df['col_name'].isnull()]['col_name'].shape
对于第一部分,我们有多种方法计算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)
请使用以下方法计算特定的列数
dataframe.columnName.isnull().sum()
你可以从非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中获取迭代器中的元素个数
- 解析日期字符串并更改格式