Numpy: Checking if a value is NaT

前端 未结 6 1661
余生分开走
余生分开走 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:10

    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
    

    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
    


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

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


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

提交回复
热议问题