如何测试变量是否为pd.NaT?

146

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

a=pd.NaT

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

有人知道吗?有什么方法可以有效地测试 a 是否为 NaT 吗?


7
pd.isnull 也适用于 NaT(Not a Time)。 - cs95
1
pandas and numpy follow the standard that NaN does not equate to itself. so even if you typed a == a you would get False - ALollz
4
投票以重新开启,因为pandas.NaT实际上不是NumPy的NaT,并且在相等性和numpy.isnat检查中表现不同。 - user2357112
@ALollz:NumPy目前还没有实现这个功能;有一个“FutureWarning”表示他们计划这样做,但目前,numpy.datetime64('NaT') == numpy.datetime64('NaT') - user2357112
@user2357112 感谢你提醒!很好知道。 - ALollz
5个回答

218
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

请注意,pandas.isnull()pandas.isna() 的别名。 - Dima Chubarov
@DmitriChubarov,一定有些不同。我使用了这个模式:df.apply(lambda x: ... if x.time.isna() else ..., axis=1)。在这种情况下,会抛出以下错误:AttributeError: 'NaTType' object has no attribute 'isna'。但如果我使用pd.isnull(x.time),它的行为就像预期的那样。 - MikeB2019x
@MikeB2019x 你可以使用 pd.isna(x.time) - Dima Chubarov

28
pd.NaT is pd.NaT

真的

这对我有效。


19

你也可以使用 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]

9
如果它在一个 Series 中(例如 DataFrame 的列),您也可以使用 .isna():
pd.Series(pd.NaT).isna()
# 0    True
# dtype: bool

不确定这是正确的。我有一个数据框,并使用“df.apply(lambda x: ... if x.time.isna() else ..., axis=1)”语句。在这种情况下,会抛出以下错误:“AttributeError:'NaTType'对象没有'isna'属性”。 - MikeB2019x

1
这是对我有用的方法。
>>> a = pandas.NaT
>>> type(a) == pandas._libs.tslibs.nattype.NaTType
>>> True

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接