在 Numpy 中針對 NaT(不表示時間)測試各個元素


要按元素對 NaT 進行測試,請在 Python Numpy 中使用 numpy.isnat() 方法。它會針對 datetime 或 timedelta 資料型別檢查值。

條件將在輸入上廣播。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他位置,out 陣列將保留其原始值。請注意,如果透過預設 out=None 建立了未初始化的 out 陣列,則其中條件為 False 的位置仍將保持未初始化狀態。

步驟

首先,匯入必需的庫 −

import numpy as np

要按元素對 NaT 進行測試,請在 Python Numpy 中使用 numpy.isnat() 方法。它會針對 datetime 或 timedelta 資料型別檢查值 −

檢查日期。datetime64 資料型別支援字串 “NAT”,它可以是大寫/小寫字母的任意組合,表示 “Not A Time” 值 −

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

# To test element-wise for NaT, use the numpy.nat() method in Python Numpy
# It checks the for datetime or timedelta data type.

# Checking for dates
# The datetime64 data type accepts the string “NAT”,
# in any combination of lowercase/uppercase letters, for a “Not A Time” value.
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

更新於: 08-Feb-2022

5K+ 瀏覽量

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.