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

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


当前回答

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

其他回答

只是用 math.isnan(x),如果x是NaN(不是数字)则返回True,否则返回False。

因为没有人提到,还有另一个变量叫做hasnans。

df[我]。如果pandas系列中的一个或多个值为NaN, hasnans将输出为True,否则为False。注意,它不是一个函数。

熊猫版本“0.19.2”和“0.20.2”

另一种方法是dropna,检查长度是否相等:

>>> len(df.dropna()) != len(df)
True
>>> 

要找出特定列中哪些行有nan:

nan_rows = df[df['name column'].isnull()]

我一直在使用以下和类型转换为字符串,并检查nan值

   (str(df.at[index, 'column']) == 'nan')

这允许我检查一个系列中的特定值,而不只是返回如果它包含在系列中的某个地方。