【问题标题】:how to test if a variable is pd.NaT?如何测试变量是否为 pd.NaT?
【发布时间】:2018-09-01 06:48:45
【问题描述】:

我正在尝试测试我的变量之一是否为 pd.NaT。我知道它是 NaT,但它仍然无法通过测试。例如,以下代码不打印任何内容:

a=pd.NaT

if a == pd.NaT:
    print("a not NaT")

有人知道吗?有没有办法有效地测试a 是否是 NaT?

【问题讨论】:

  • pd.isnull 也适用于 NaT。
  • pandasnumpy 遵循NaN 不等同于自身的标准。所以即使你输入a == a,你也会得到False
  • 投票重新打开,因为 pandas.NaT 实际上不是 NumPy NaT,它在相等和 numpy.isnat 检查中的行为不同。
  • @ALollz:NumPy 实际上还没有这样做;有一个FutureWarning 说他们计划这样做,但现在是numpy.datetime64('NaT') == numpy.datetime64('NaT')

标签: python pandas unit-testing datetime nan


【解决方案1】:

Pandas NaT 的行为类似于浮点 NaN,因为它不等于自身。相反,您可以使用pandas.isnull

In [21]: pandas.isnull(pandas.NaT)
Out[21]: True

这也为 None 和 NaN 返回 True

从技术上讲,您还可以使用 x != x 来检查 Pandas NaT,遵循用于浮点 NaN 的常见模式。但是,这可能会导致 NumPy NaT 出现问题,它们看起来非常相似并代表相同的概念,但实际上是具有不同行为的不同类型:

In [29]: x = pandas.NaT

In [30]: y = numpy.datetime64('NaT')

In [31]: x != x
Out[31]: True

In [32]: y != y
/home/i850228/.local/lib/python3.6/site-packages/IPython/__main__.py:1: FutureWarning: In the future, NAT != NAT will be True rather than False.
  # encoding: utf-8
Out[32]: False

numpy.isnat,用于检查 NumPy NaT 的函数也因 Pandas NaT 而失败:

In [33]: numpy.isnat(pandas.NaT)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-39a66bbf6513> in <module>()
----> 1 numpy.isnat(pandas.NaT)

TypeError: ufunc 'isnat' is only defined for datetime and timedelta.

pandas.isnull 适用于 Pandas 和 NumPy NaT,所以这可能是要走的路:

In [34]: pandas.isnull(pandas.NaT)
Out[34]: True

In [35]: pandas.isnull(numpy.datetime64('NaT'))
Out[35]: True

【讨论】:

    【解决方案2】:

    您还可以将 pandas.isna() 用于 pandas.NaT、numpy.nan 或 None:

    import pandas as pd
    import numpy as np
    
    x = (pd.NaT, np.nan, None)
    [pd.isna(i) for i in x]
    
    Output:
    [True, True, True]
    

    【讨论】:

      【解决方案3】:
      pd.NaT is pd.NaT
      

      是的

      这对我有用。

      【讨论】:

        【解决方案4】:

        如果它在Series(例如DataFrame 列)中,您也可以使用.isna()

        pd.Series(pd.NaT).isna()
        # 0    True
        # dtype: bool
        

        【讨论】:

          【解决方案5】:

          这对我有用

          >>> a = pandas.NaT
          >>> type(a) == pandas._libs.tslibs.nattype.NaTType
          >>> True
          

          【讨论】:

            猜你喜欢
            • 2011-04-07
            • 2019-01-03
            • 1970-01-01
            • 2016-07-27
            • 2011-04-09
            • 1970-01-01
            • 2012-06-09
            • 2017-10-11
            • 2011-08-05
            相关资源
            最近更新 更多