Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Checking if a value is NaT

Tags:

python

numpy

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.

like image 671
user65 Avatar asked Jul 21 '16 16:07

user65


People also ask

What is NumPy NaT?

Test element-wise for NaT (not a time) and return result as a boolean array.

Is NaT same as NaN?

NaN doesn't equal NaN . And NaT doesn't equal NaT . But None does equal None .

What is NaT Python pandas?

nat means a missing date. Copy. df['time'] = pd. Timestamp('20211225') df. loc['d'] = np.


1 Answers

pandas can check for NaT with 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:

>>> 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)

like image 85
MSeifert Avatar answered Sep 29 '22 01:09

MSeifert