首页 文章

如何检查Pandas DataFrame中的任何值是否为NaN

提问于
浏览
292

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

我知道函数 pd.isnan ,但这会为每个元素返回一个布尔数据框架 . This post就在这里也没有完全回答我的问题 .

12 回答

  • 352

    由于 pandas 必须为 DataFrame.dropna() 找到它,我看了看它们是如何实现它的,并发现它们使用 DataFrame.count() ,它计算 DataFrame 中的所有非空值 . 参看pandas source code . 我没有对这种技术进行基准测试,但我认为图书馆的作者可能已经做了明智的选择 .

  • 22

    jwilner 's response is spot on. I was exploring to see if there'是一个更快的选择,因为根据我的经验,求平面阵列(奇怪地)比计数更快 . 这段代码似乎更快:

    df.isnull().values.any()
    

    例如:

    In [2]: df = pd.DataFrame(np.random.randn(1000,1000))
    
    In [3]: df[df > 0.9] = pd.np.nan
    
    In [4]: %timeit df.isnull().any().any()
    100 loops, best of 3: 14.7 ms per loop
    
    In [5]: %timeit df.isnull().values.sum()
    100 loops, best of 3: 2.15 ms per loop
    
    In [6]: %timeit df.isnull().sum().sum()
    100 loops, best of 3: 18 ms per loop
    
    In [7]: %timeit df.isnull().values.any()
    1000 loops, best of 3: 948 µs per loop
    

    df.isnull().sum().sum() 有点慢,但当然还有其他信息 - NaNs 的数量 .

  • 7

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

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

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

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

    适用于分类变量,而不是在有许多唯一值时 .

  • 1

    由于没有人提到,只有另一个名为 hasnans 的变量 .

    如果pandas Series中的一个或多个值为NaN, df[i].hasnans 将输出到 True ,否则为 False . 请注意,它不是一个功能 .

    熊猫版'0.19.2'和'0.20.2'

  • 1

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

  • 10

    或者您可以在 DF 上使用 .info() ,例如:

    df.info(null_counts=True) 返回列中的non_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
    
  • 4

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

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

    或者,如果您需要提取这些行并检查它们:

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

    你有几个选择 .

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(np.random.randn(10,6))
    # Make a few areas have NaN values
    df.iloc[1:3,1] = np.nan
    df.iloc[5,3] = np.nan
    df.iloc[7:9,5] = np.nan
    

    现在数据框看起来像这样:

    0         1         2         3         4         5
    0  0.520113  0.884000  1.260966 -0.236597  0.312972 -0.196281
    1 -0.837552       NaN  0.143017  0.862355  0.346550  0.842952
    2 -0.452595       NaN -0.420790  0.456215  1.203459  0.527425
    3  0.317503 -0.917042  1.780938 -1.584102  0.432745  0.389797
    4 -0.722852  1.704820 -0.113821 -1.466458  0.083002  0.011722
    5 -0.622851 -0.251935 -1.498837       NaN  1.098323  0.273814
    6  0.329585  0.075312 -0.690209 -3.807924  0.489317 -0.841368
    7 -1.123433 -1.187496  1.868894 -2.046456 -0.949718       NaN
    8  1.133880 -0.110447  0.050385 -1.158387  0.188222       NaN
    9 -0.513741  1.196259  0.704537  0.982395 -0.585040 -1.693810
    
    • Option 1df.isnull().any().any() - 返回一个布尔值

    你知道 isnull() 会返回一个像这样的数据帧:

    0      1      2      3      4      5
    0  False  False  False  False  False  False
    1  False   True  False  False  False  False
    2  False   True  False  False  False  False
    3  False  False  False  False  False  False
    4  False  False  False  False  False  False
    5  False  False  False   True  False  False
    6  False  False  False  False  False  False
    7  False  False  False  False  False   True
    8  False  False  False  False  False   True
    9  False  False  False  False  False  False
    

    如果您将其设为 df.isnull().any() ,则只能找到具有 NaN 值的列:

    0    False
    1     True
    2    False
    3     True
    4    False
    5     True
    dtype: bool
    

    还有一个 .any() 会告诉你是否有以上任何一个 True

    > df.isnull().any().any()
    True
    
    • Option 2df.isnull().sum().sum() - 返回 NaN 值总数的整数:

    这与 .any().any() 的操作方式相同,首先给出一列中 NaN 值的总和,然后是这些值的总和:

    df.isnull().sum()
    0    0
    1    2
    2    0
    3    1
    4    0
    5    2
    dtype: int64
    

    最后,要获取DataFrame中NaN值的总数:

    df.isnull().sum().sum()
    5
    
  • 14

    这是另一种有趣的方法,即找到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
    
  • 1

    df.isnull().any().any() 应该这样做 .

  • 113

    添加到Hobs的精彩答案,我对Python和Pandas都很陌生,所以请指出我是不是错了 .

    要找出哪些行具有NaN:

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

    通过将any()的轴指定为1来检查行中是否存在“True”,将执行相同的操作而无需转置 .

相关问题