问题描述
我正在尝试测试我的变量之一是否是pd.NaT.我知道它是NaT,但仍然无法通过测试.例如,以下代码不显示任何内容:
I'm trying to test if one of my variables is pd.NaT. I know it is NaT, and still it won't pass the test. As an example, the following code prints nothing :
a=pd.NaT
if a == pd.NaT:
print("a not NaT")
有人知道吗?有没有一种方法可以有效地测试a
是否为NaT?
Does anyone have a clue ? Is there a way to effectively test if a
is NaT?
推荐答案
熊猫NaT
的行为类似于浮点NaN
,因为它不等于自身.相反,您可以使用pandas.isnull
:
Pandas NaT
behaves like a floating-point NaN
, in that it's not equal to itself. Instead, you can use pandas.isnull
:
In [21]: pandas.isnull(pandas.NaT)
Out[21]: True
这还会为None和NaN返回True
.
This also returns True
for None and NaN.
从技术上讲,您还可以按照用于浮点NaN的通用模式,用x != x
检查熊猫NaT
.但是,这可能会导致NumPy NaT出现问题,它们看起来非常相似并且代表相同的概念,但实际上是具有不同行为的不同类型:
Technically, you could also check for Pandas NaT
with x != x
, following a common pattern used for floating-point NaN. However, this is likely to cause issues with NumPy NaTs, which look very similar and represent the same concept, but are actually a different type with different behavior:
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
的功能)也因熊猫NaT
而失败:
numpy.isnat
, the function to check for NumPy NaT
, also fails with a 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,所以这可能是解决方法:
pandas.isnull
works for both Pandas and NumPy NaTs, so it's probably the way to go:
In [34]: pandas.isnull(pandas.NaT)
Out[34]: True
In [35]: pandas.isnull(numpy.datetime64('NaT'))
Out[35]: True
这篇关于如何测试变量是否为pd.NaT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!