在Python Pandas中,检查DataFrame是否有一个(或多个)NaN值的最佳方法是什么?
我知道函数pd。isnan,但这将返回每个元素的布尔值的DataFrame。这篇文章也没有完全回答我的问题。
在Python Pandas中,检查DataFrame是否有一个(或多个)NaN值的最佳方法是什么?
我知道函数pd。isnan,但这将返回每个元素的布尔值的DataFrame。这篇文章也没有完全回答我的问题。
当前回答
或者你可以在DF上使用.info(),例如:
df.info(null_counts=True)返回列中非_null的行数,例如:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3276314 entries, 0 to 3276313
Data columns (total 10 columns):
n_matches 3276314 non-null int64
avg_pic_distance 3276314 non-null float64
其他回答
或者你可以在DF上使用.info(),例如:
df.info(null_counts=True)返回列中非_null的行数,例如:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3276314 entries, 0 to 3276313
Data columns (total 10 columns):
n_matches 3276314 non-null int64
avg_pic_distance 3276314 non-null float64
df.apply(axis=0, func=lambda x : any(pd.isnull(x)))
将检查每一列是否包含Nan。
你不仅可以检查是否有'NaN'存在,还可以使用下面的方法得到'NaN'在每一列中的百分比,
df = pd.DataFrame({'col1':[1,2,3,4,5],'col2':[6,np.nan,8,9,10]})
df
col1 col2
0 1 6.0
1 2 NaN
2 3 8.0
3 4 9.0
4 5 10.0
df.isnull().sum()/len(df)
col1 0.0
col2 0.2
dtype: float64
由于pandas必须为DataFrame.dropna()找到这一点,我看了看他们是如何实现它的,并发现他们使用了DataFrame.count(),它会计数DataFrame中的所有非空值。参考熊猫源代码。我还没有对这种技术进行基准测试,但我认为库的作者可能已经就如何实现它做出了明智的选择。
import missingno as msno
msno.matrix(df) # just to visualize. no missing value.