如何测试变量是否为 pd.NaT? [英] how to test if a variable is pd.NaT?

查看:55
本文介绍了如何测试变量是否为 pd.NaT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试我的变量之一是否是 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?

推荐答案

Pandas 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.

从技术上讲,您还可以使用 x != x 检查 Pandas NaT,遵循用于浮点 NaN 的常见模式.但是,这很可能会导致 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 的函数,也因 Pandas 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 NaTs,所以它可能是要走的路:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆