在 Numpy 中逐元素测试 NaT(非时间)
numpyserver side programmingprogramming更新于 2025/9/26 6:22:17
要逐元素测试 NaT,请使用 Python Numpy 中的 numpy.isnat() 方法。该方法检查 datetime 或 timedelta 数据类型的值。
条件通过输入进行广播。在条件为 True 的位置,输出数组将设置为 ufunc 的结果。在其他位置,输出数组将保留其原始值。请注意,如果通过默认 out=None 创建了未初始化的输出数组,则其中条件为 False 的位置将保持未初始化状态。
步骤
首先,导入所需的库 −
import numpy as np
要逐元素测试 NaT,请使用 Python Numpy 中的 numpy.isnat() 方法。检查 datetime 或 timedelta 数据类型的值是否为 −
检查日期。datetime64 数据类型接受字符串"NAT"(任意大小写字母组合),表示"非时间"值 −
print("Check for NaT? ", np.isnat(np.datetime64("NaT")))
print("Check for NaT? ", np.isnat(np.datetime64("2021-12-22")))
print("Check for NaT? ", np.isnat(np.datetime64('2021-12', 'D')))
print("Check for NaT? ", np.isnat(np.datetime64(1, 'Y')))
print("Check for NaT? ", np.isnat(np.datetime64('2005-02-25T03:30')))
print("Check for NaT? ", np.isnat(np.datetime64('nat')))
print("Check for NaT? ", np.isnat(np.datetime64("5")))
print("Check for NaT? ", np.isnat(np.datetime64('nAt')))
示例
import numpy as np
# 要逐元素测试 NaT,请使用 Python Numpy 中的 numpy.nat() 方法。
# 它检查 datetime 或 timedelta 数据类型。
# 检查日期
# datetime64 数据类型接受字符串"NAT",
# 以任意大小写字母组合表示"非时间"值。
print("Check for NaT? ", np.isnat(np.datetime64("NaT")))
print("Check for NaT? ", np.isnat(np.datetime64("2021-12-22")))
print("Check for NaT? ", np.isnat(np.datetime64('2021-12', 'D')))
print("Check for NaT? ", np.isnat(np.datetime64(1, 'Y')))
print("Check for NaT? ", np.isnat(np.datetime64('2005-02-25T03:30')))
print("Check for NaT? ", np.isnat(np.datetime64('nat')))
print("Check for NaT? ", np.isnat(np.datetime64("5")))
print("Check for NaT? ", np.isnat(np.datetime64('nAt')))
输出
Check for NaT? True Check for NaT? False Check for NaT? False Check for NaT? False Check for NaT? False Check for NaT? True Check for NaT? False Check for NaT? True

