测试 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.