在NumPy中测试数组值的有限性并将结果存储到新的位置


要测试数组值的有限性,请在 Python NumPy 中使用 **numpy.isfinite()** 方法。我们将存储结果的新位置是一个新数组。如果 x 不是正无穷大、负无穷大或 NaN,则返回 True;否则返回 false。如果 x 是标量,则这是一个标量。

此条件会广播到输入上。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他位置,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化状态。

步骤

首先,导入所需的库:

import numpy as np

创建一个包含一些无穷大值的数组:

arr = np.array([1, 2, 10, 50, -np.inf, 0., np.inf])

显示数组:

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, 5, 5])

要测试数组值的有限性,请在 Python NumPy 中使用 numpy.isfinite() 方法。我们将存储结果的新位置是 arrRes:

print("
Test array for finiteness...
",np.isfinite(arr, arrRes))

检查存储结果的新数组的值:

print("
Result...
",arrRes)

示例

import numpy as np

# Create an array with some inf values
arr = np.array([1, 2, 10, 50, -np.inf, 0., np.inf])

# 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, 5, 5]) # To test array values for finiteness, use the numpy.isfinite() method in Python Numpy # The new location where we will store the result is arrRes print("
Test array for finiteness...
",np.isfinite(arr, arrRes)) # Check the value of the new array where our result is stored print("
Result...
",arrRes)

输出

Array...
[ 1. 2. 10. 50. -inf 0. inf]

Our Array type...
float64

Our Array Dimensions...
1

Number of elements...
7

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

Result...
[1 1 1 1 0 1 0]

更新于:2022年2月7日

110 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.