我想找出我的数据的每一列中NaN的数量。
当前回答
我使用这个循环来计算每一列的缺失值:
# check missing values
import numpy as np, pandas as pd
for col in df:
print(col +': '+ np.str(df[col].isna().sum()))
其他回答
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
根据给出的答案和一些改进,这是我的方法
def PercentageMissin(Dataset):
"""this function will return the percentage of missing values in a dataset """
if isinstance(Dataset,pd.DataFrame):
adict={} #a dictionary conatin keys columns names and values percentage of missin value in the columns
for col in Dataset.columns:
adict[col]=(np.count_nonzero(Dataset[col].isnull())*100)/len(Dataset[col])
return pd.DataFrame(adict,index=['% of missing'],columns=adict.keys())
else:
raise TypeError("can only be used with panda dataframe")
我使用这个循环来计算每一列的缺失值:
# check missing values
import numpy as np, pandas as pd
for col in df:
print(col +': '+ np.str(df[col].isna().sum()))
自从pandas 0.14.1以来,我的建议在value_counts方法中有一个关键字参数已经实现:
import pandas as pd
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
for col in df:
print df[col].value_counts(dropna=False)
2 1
1 1
NaN 1
dtype: int64
NaN 2
1 1
dtype: int64
如果只是在pandas列中计算nan值,这里是一个快速的方法
import pandas as pd
## df1 as an example data frame
## col1 name of column for which you want to calculate the nan values
sum(pd.isnull(df1['col1']))
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获取迭代器中的元素个数
- 解析日期字符串并更改格式