python - Numpy:检查值是否为 NaT

标签 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''

如何检查 datetime64 是否为 NaT?我似乎无法从文档中挖掘出任何东西。我知道 Pandas 可以做到,但我不想为这么基本的东西添加依赖项。

最佳答案

可以使用 pandas.isnull 检查 NaT :

>>> import numpy as np
>>> import pandas as pd
>>> pd.isnull(np.datetime64('NaT'))
True

如果你不想使用 pandas 也可以定义自己的函数(部分取自 pandas 源):

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

这可以正确识别 NaT 值:

>>> isnat(np.datetime64('NAT'))
True

>>> isnat(np.timedelta64('NAT'))
True

并意识到它是否不是日期时间或时间增量:

>>> isnat(np.timedelta64('NAT').view('i8'))
False

将来在 numpy 代码中可能会有一个 isnat 函数,至少他们有一个(当前打开的)关于它的拉取请求:Link to the PR (NumPy github)

关于python - Numpy:检查值是否为 NaT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38509538/

相关文章:

python - 如何让 matplotlib 按照与列表相同的顺序对条形图进行排序?

python - 将 Pandas 系列向量化查找到字典

python - 快速半正弦逼近(Python/Pandas)

python - 像在 Postman 中一样在 Python 中获取访问 token

python - 是否可以从另一个 python 脚本中运行一个 python 脚本?

python - 使用用户输入调用特定的 python 类

python:从txt文件的行创建字典

python - 查找与已知平面正交的平面

python - Pandas DataFrame 上的特定组计算

python - 将 Fortran 复数读入 Python