測試 NumPy 陣列中的 NaT 值並將結果儲存到新位置


要測試陣列中的 NaT 值,請在 Python NumPy 中使用 **numpy.isnat()** 方法。我們將把結果儲存到一個新的陣列中。

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

out 是儲存結果的位置。如果提供,則其形狀必須與輸入資料廣播到的形狀相同。如果未提供或為 None,則返回一個新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出的數量。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個包含一些 NaT 和日期值的陣列:

arr = np.array(["2021-12-22", "NaT", "NAT", "nAt", '2021-12'], dtype="datetime64[ns]")

顯示陣列:

print("Array...
", arr)

獲取陣列的型別:

print("
Our Array type...
", arr.dtype)

獲取陣列的維度:

print("
Our Array Dimensions...
",arr.ndim)

獲取陣列中元素的數量:

print("
Number of elements...
", arr.size)

建立一個具有相同形狀的另一個數組來儲存結果:

arrRes = np.array([5, 5, 5, 5, 5])

要測試陣列中的 NaT 值,請在 Python NumPy 中使用 numpy.isnat() 方法。我們將把結果儲存到 arrRes 中:

print("
Test array for NaT...
",np.isnat(arr, arrRes))

檢查儲存結果的新陣列的值:

print("
Result...
",arrRes)

示例

import numpy as np

# Create an array with some NaT and date values
arr = np.array(["2021-12-22", "NaT", "NAT", "nAt", '2021-12'], dtype="datetime64[ns]")

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimensions...
",arr.ndim) # Get the number of elements in the Array print("
Number of elements...
", arr.size) # Create another array with the same shape to store the result arrRes = np.array([5, 5, 5, 5, 5]) # To test array values for NaT, use the numpy.isnat() method in Python Numpy # The new location where we will store the result is arrRes print("
Test array for NaT...
",np.isnat(arr, arrRes)) # Check the value of the new array where our result is stored print("
Result...
",arrRes)

輸出

Array...
['2021-12-22T00:00:00.000000000' 'NaT'
'NaT' 'NaT'
'2021-12-01T00:00:00.000000000']

Our Array type...
datetime64[ns]

Our Array Dimensions...
1

Number of elements...
5

Test array for NaT...
[0 1 1 1 0]

Result...
[0 1 1 1 0]

更新於:2022年2月8日

瀏覽量:135

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.