Python Numpy:检查值是否为 NaT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38509538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Numpy: Checking if a value is NaT
提问by user65
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''
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.
如何检查 datetime64 是否为 NaT?我似乎无法从文档中挖掘任何东西。我知道 Pandas 可以做到,但我不想为如此基本的东西添加依赖项。
采纳答案by Vadim Shkaberda
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.
简介:这个答案是在 Numpy 是 1.11 版的时候写的,NAT 比较的行为应该从 1.12 版开始改变。显然情况并非如此,答案的第二部分出错了。答案的第一部分可能不适用于新版本的 numpy。请确保您已检查以下 MSeifert 的答案。
当你第一次进行比较时,你总是有一个警告。但同时返回的比较结果是正确的:
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
If you want to suppress the warning you can use the catch_warningscontext manager:
如果要取消警告,可以使用catch_warnings上下文管理器:
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
EDIT:编辑:出于某种原因,Numpy 1.12 版中 NAT 比较的行为没有改变,所以下一个代码结果不一致。
And finally you might check numpy version to handle changed behavior since version 1.12.0:
最后,您可能会检查 numpy 版本以处理自 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')
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')
EDIT:编辑:作为MSeifertMSeifert提到,Numpy 包含
isnat
isnat
自 1.13 版以来的功能。回答by MSeifert
pandascan check for NaT
with pandas.isnull
:
大熊猫可以检查NaT
有pandas.isnull
:
>>> import numpy as np
>>> import pandas as pd
>>> pd.isnull(np.datetime64('NaT'))
True
If you don't want to use pandas you can also define your own function (parts are taken from the pandas source):
如果你不想使用熊猫,你也可以定义你自己的函数(部分取自熊猫源):
nat_as_integer = np.datetime64('NAT').view('i8')
def isnat(your_datetime):
dtype_string = str(your_datetime.dtype)
if 'datetime64' in dtype_string or 'timedelta64' in dtype_string:
return your_datetime.view('i8') == nat_as_integer
return False # it can't be a NaT if it's not a dateime
This correctly identifies NaT values:
这可以正确识别 NaT 值:
>>> isnat(np.datetime64('NAT'))
True
>>> isnat(np.timedelta64('NAT'))
True
And realizes if it's not a datetime or timedelta:
并意识到它不是日期时间或时间增量:
>>> isnat(np.timedelta64('NAT').view('i8'))
False
In the future there might be an isnat
-function in the numpy code, at least they have a (currently open) pull request about it: Link to the PR (NumPy github)
将来isnat
numpy 代码中可能会有一个-function,至少他们有一个(当前打开的)关于它的拉取请求:链接到 PR (NumPy github)
回答by MSeifert
Since NumPy version 1.13 it contains an isnat
function:
从 NumPy 1.13 版开始,它包含一个isnat
函数:
>>> import numpy as np
>>> np.isnat(np.datetime64('nat'))
True
It also works for arrays:
它也适用于数组:
>>> np.isnat(np.array(['nat', 1, 2, 3, 4, 'nat', 5], dtype='datetime64[D]'))
array([ True, False, False, False, False, True, False], dtype=bool)
回答by CodeCabbie
Very simpleand surprisingly fast: (without numpy or pandas)
非常简单且速度惊人:(没有 numpy 或 pandas)
str( myDate ) == 'NaT' # True if myDate is NaT
Ok, it's a little nasty, but given the ambiguity surrounding 'NaT' it does the job nicely.
好吧,这有点讨厌,但考虑到围绕“NaT”的模糊性,它很好地完成了这项工作。
It's also useful when comparing two dates either of which might be NaT as follows:
在比较两个可能是 NaT 的两个日期时,它也很有用,如下所示:
str( date1 ) == str( date1 ) # True
str( date1 ) == str( NaT ) # False
str( NaT ) == str( date1 ) # False
wait for it...
str( NaT ) == str( Nat ) # True (hooray!)
回答by rusty
This approach avoids the warnings while preserving the array-oriented evaluation.
这种方法避免了警告,同时保留了面向数组的评估。
import numpy as np
def isnat(x):
"""
datetime64 analog to isnan.
doesn't yet exist in numpy - other ways give warnings
and are likely to change.
"""
return x.astype('i8') == np.datetime64('NaT').astype('i8')
回答by Guest
Another way would be to catch the exeption:
另一种方法是抓住例外:
def is_nat(npdatetime):
try:
npdatetime.strftime('%x')
return False
except:
return True