numpy:检查值是否为NaT [英] Numpy: Checking if a value is NaT

查看:245
本文介绍了numpy:检查值是否为NaT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

nat = np.datetime64('NaT')
nat == nat
>> FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.

np.isnan(nat)
>> TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

如何检查datetime64是否为NaT?我似乎无法从文档中挖掘任何东西.我知道Pandas可以做到,但我不希望对如此基本的东西添加依赖.

How can I check if a datetime64 is NaT? I can't seem to dig anything out of the docs. I know Pandas can do it, but I'd rather not add a dependency for something so basic.

推荐答案

INTRO:这个答案是在Numpy版本为1.11,而NAT比较的行为应该从版本1.12开始改变的时候写的. .显然不是这种情况,答案的第二部分就错了.答案的第一部分可能不适用于新版本的numpy.确保已检查以下MSeifert的答案.


第一次进行比较时,始终会发出警告.但是同时返回的比较结果是正确的:

INTRO: This answer was written in a time when Numpy was version 1.11 and behaviour of NAT comparison was supposed to change since version 1.12. Clearly that wasn't the case and the second part of answer became wrong. The first part of answer may be not applicable for new versions of numpy. Be sure you've checked MSeifert's answers below.


When you make a comparison at the first time, you always have a warning. But meanwhile returned result of comparison is correct:

import numpy as np    
nat = np.datetime64('NaT')

def nat_check(nat):
    return nat == np.datetime64('NaT')    

nat_check(nat)
Out[4]: FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
True

nat_check(nat)
Out[5]: True

如果您想取消该警告,则可以使用 catch_warnings 上下文管理器:

If you want to suppress the warning you can use the catch_warnings context manager:

import numpy as np
import warnings

nat = np.datetime64('NaT')

def nat_check(nat):
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return nat == np.datetime64('NaT')    

nat_check(nat)
Out[5]: True


出于某些原因,Numpy版本1.12中的NAT比较行为没有改变,因此下一个代码证明是不一致的.


For some reason behavior of NAT comparison in Numpy version 1.12 wasn't change, so the next code turned out to be inconsistent.

最后,您可能会检查numpy版本以处理自1.12.0版本以来的更改行为:

And finally you might check numpy version to handle changed behavior since version 1.12.0:

def nat_check(nat):
    if [int(x) for x in np.__version__.split('.')[:-1]] > [1, 11]:
        return nat != nat
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return nat == np.datetime64('NaT')


编辑:正如 MSeifert 所述,Numpy从1.13版开始包含isnat函数.


As MSeifert mentioned, Numpy contains isnat function since version 1.13.

这篇关于numpy:检查值是否为NaT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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