Numpy: Checking if a value is NaT

前端 未结 6 1659
余生分开走
余生分开走 2020-12-23 21:12
nat = np.datetime64(\'NaT\')
nat == nat
>> FutureWarning: In the future, \'NAT == x\' and \'x == NAT\' will always be False.

np.isnan(nat)
>> TypeError:         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 22:02

    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)

提交回复
热议问题