在Python Pandas中,检查DataFrame是否有一个(或多个)NaN值的最佳方法是什么?

我知道函数pd。isnan,但这将返回每个元素的布尔值的DataFrame。这篇文章也没有完全回答我的问题。


当前回答

条形表示缺少的值

import missingno
missingno.bar(df)# will give you exact no of values and values missing

其他回答

如果你需要知道有多少行有“一个或多个nan”:

df.isnull().T.any().T.sum()

或者如果你需要取出这些行并检查它们:

nan_rows = df[df.isnull().T.any()]

根据您正在处理的数据类型,您还可以在执行EDA时通过将dropna设置为False来获得每列的值计数。

for col in df:
   print df[col].value_counts(dropna=False)

适用于分类变量,但当你有很多唯一值时就不那么适用了。

条形表示缺少的值

import missingno
missingno.bar(df)# will give you exact no of values and values missing
df.apply(axis=0, func=lambda x : any(pd.isnull(x)))

将检查每一列是否包含Nan。

下面是另一种有趣的查找null并替换为计算值的方法

    #Creating the DataFrame

    testdf = pd.DataFrame({'Tenure':[1,2,3,4,5],'Monthly':[10,20,30,40,50],'Yearly':[10,40,np.nan,np.nan,250]})
    >>> testdf2
       Monthly  Tenure  Yearly
    0       10       1    10.0
    1       20       2    40.0
    2       30       3     NaN
    3       40       4     NaN
    4       50       5   250.0

    #Identifying the rows with empty columns
    nan_rows = testdf2[testdf2['Yearly'].isnull()]
    >>> nan_rows
       Monthly  Tenure  Yearly
    2       30       3     NaN
    3       40       4     NaN

    #Getting the rows# into a list
    >>> index = list(nan_rows.index)
    >>> index
    [2, 3]

    # Replacing null values with calculated value
    >>> for i in index:
        testdf2['Yearly'][i] = testdf2['Monthly'][i] * testdf2['Tenure'][i]
    >>> testdf2
       Monthly  Tenure  Yearly
    0       10       1    10.0
    1       20       2    40.0
    2       30       3    90.0
    3       40       4   160.0
    4       50       5   250.0