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

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


当前回答

由于pandas必须为DataFrame.dropna()找到这一点,我看了看他们是如何实现它的,并发现他们使用了DataFrame.count(),它会计数DataFrame中的所有非空值。参考熊猫源代码。我还没有对这种技术进行基准测试,但我认为库的作者可能已经就如何实现它做出了明智的选择。

其他回答

加上霍布斯的精彩回答,我对Python和熊猫很陌生,所以如果我错了,请指出来。

要找出哪些行有nan:

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

将执行相同的操作,而不需要通过将any()的轴指定为1来检查'True'是否在行中存在。

下面是另一种有趣的查找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

由于pandas必须为DataFrame.dropna()找到这一点,我看了看他们是如何实现它的,并发现他们使用了DataFrame.count(),它会计数DataFrame中的所有非空值。参考熊猫源代码。我还没有对这种技术进行基准测试,但我认为库的作者可能已经就如何实现它做出了明智的选择。

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

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

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

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

我建议使用值属性作为数组的计算是更快的。

arr = np.random.randn(100, 100)
arr[40, 40] = np.nan
df = pd.DataFrame(arr)

%timeit np.isnan(df.values).any()  # 7.56 µs
%timeit np.isnan(df).any()         # 627 µs
%timeit df.isna().any(axis=None)   # 572 µs

结果:

7.56 µs ± 447 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
627 µs ± 40.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
572 µs ± 15.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

注意:你需要在Jupyter笔记本上运行%timeit才能工作