我正在尝试测试我的变量之一是否是 pd.NaT。我知道它是 NaT,但它仍然无法通过测试。例如,以下代码不打印任何内容:
a=pd.NaT
if a == pd.NaT:
print("a not NaT")
有人知道吗?有没有办法有效测试 a
是否为 NaT?
最佳答案
Pandas NaT
的行为类似于浮点 NaN
,因为它不等于自身。相反,您可以使用pandas.isnull
:
In [21]: pandas.isnull(pandas.NaT)
Out[21]: True
对于 None 和 NaN,这也会返回 True
。
从技术上讲,您还可以按照用于浮点 NaN 的常见模式,使用 x != x
检查 Pandas NaT
。但是,这可能会导致 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
关于python - 如何测试变量是否为 pd.NaT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435317/