【问题标题】:How to check if Pandas/NumPy arbitrary object contains or IS NaT/NaN/Null如何检查 Pandas/NumPy 任意对象是否包含 NaT/NaN/Null
【发布时间】:2020-03-24 00:35:19
【问题描述】:

我想检查一个 Pandas 对象是否是/包含任何 Null/NaN/NaT 值,但如果该对象是一个列表还是一个奇异值,我事先没有任何信息。

我试过了

x = [1,2,3,pd.NaT]
if pd.notnull(x):
    ...

但是如果对象x是一个列表,它返回这个值错误(由于它返回一个布尔值数组):

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如果我这样做:

x = pd.NaT
if pd.notnull(x).any():
   ...

如果我收到一个奇异值,它会返回此错误:

AttributeError: 'bool' object has no attribute 'any'

能够处理可能包含 NaN 和 NaN 本身的两个列表的最干净的方法是什么?

【问题讨论】:

    标签: python pandas null


    【解决方案1】:

    x 包裹在列表中并传递给pd.notna 并链接any。它之所以有效,是因为 pd.notna 返回 numpy ndarray。因此,any 实际上是ndarray.any。当在没有axis 参数的情况下调用numpy ndarray.any 时,它将检查所有维度。因此,它适用于列表x 或单个值x

    x = [1,2,3,pd.NaT]
    
    In [369]: pd.notna([x])
    Out[369]: array([[ True,  True,  True, False]]) #it is 2d-array
    
    In [370]: type(pd.notna([x]))
    Out[370]: numpy.ndarray
    
    In [373]: pd.notna([x]).any()  #`ndarray.any` checks on all dimensions of this 2d-array
    Out[373]: True
    
    In [374]: pd.notna([x]).all()  #`ndarray.all` checks on all dimensions of this 2d-array
    Out[374]: False
    

    x是单身pd.NaT

    x = pd.NaT
    
    In [377]: pd.notna([x])
    Out[377]: array([False])  #it is 1d-array
    
    In [378]: pd.notna([x]).any()
    Out[378]: False
    
    In [379]: pd.notna([x]).all()
    Out[379]: False
    

    【讨论】:

    • 谢谢!有用。出于我的目的,我需要使用 all() 而不是 any() 链接。
    • 有一点需要注意,它不适用于嵌入式列表。例如。 x = [1,2,3,[1,pd.NaT]]
    • 是的,它不适用于嵌入列表,因为 pd.notna 不会递归检查嵌套元素。在嵌入列表中,它将每个子列表视为一个整体元素,因此除非子列表为空,否则它会在子列表上返回True
    【解决方案2】:

    如果您只需要知道数据框中的任何值是否为NaN,那么您可以简单地做

    if df.isnull().any().any():
        # NaN present(s)
        do_something()
    

    【讨论】:

      猜你喜欢
      • 2013-09-12
      • 2021-10-29
      • 1970-01-01
      • 2013-10-13
      • 2018-03-20
      • 2016-11-25
      • 2022-11-09
      • 1970-01-01
      • 2015-06-14
      相关资源
      最近更新 更多