比较两个包含 Inf 值的 NumPy 数组,并返回逐元素最小值


要比较包含一些 Inf 值的两个数组并返回逐元素最小值,请在 Python NumPy 中使用 **numpy.minimum()** 方法。返回值为 True 或 False。返回 x1 和 x2 的逐元素最小值。如果 x1 和 x2 都是标量,则这是一个标量。

比较两个数组并返回一个新数组,其中包含逐元素最小值。如果被比较的元素之一是 NaN,则返回该元素。如果两个元素都是 NaN,则返回第一个。后一种区别对于复数 NaN 非常重要,复数 NaN 定义为实部或虚部至少有一个是 NaN。最终效果是 NaN 会被传播。

NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持各种硬件和计算平台,并且可以很好地与分布式、GPU 和稀疏数组库协同工作。

步骤

首先,导入所需的库:

import numpy as np

使用 array() 方法创建两个二维 NumPy 数组。我们插入了一些包含 inf(无穷大)值的元素:

arr1 = np.array([[14, np.Inf, 17],[25, 11, 0]])
arr2 = np.array([[8, np.Inf, np.Inf],[22, 0, 26]])

显示数组:

print("Array 1...
", arr1) print("
Array 2...
", arr2)

获取数组的类型:

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

获取数组的维度:

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

获取数组的形状:

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

要比较包含一些 Inf 值的两个数组并返回逐元素最小值,请在 Python NumPy 中使用 numpy.minimum() 方法。返回值为 True 或 False:

print("
Result (minimum)...
",np.minimum(arr1, arr2))

示例

Open Compiler
import numpy as np # Creating two 2D numpy array using the array() method # We have inserted elements with some inf (infinity) values arr1 = np.array([[14, np.Inf, 17],[25, 11, 0]]) arr2 = np.array([[8, np.Inf, np.Inf],[22, 0, 26]]) # Display the arrays print("Array 1...", arr1) print("Array 2...", arr2) # Get the type of the arrays print("Our Array 1 type...", arr1.dtype) print("Our Array 2 type...", arr2.dtype) # Get the dimensions of the Arrays print("Our Array 1 Dimensions...",arr1.ndim) print("Our Array 2 Dimensions...",arr2.ndim) # Get the shape of the Arrays print("Our Array 1 Shape...",arr1.shape) print("Our Array 2 Shape...",arr2.shape) # To compare two arrays with some Inf values and return the elementwise minimum, use the numpy.minimum() method in Python Numpy # Return value is either True or False print("Result (minimum)...",np.minimum(arr1, arr2))

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Array 1...
[[14. inf 17.]
[25. 11. 0.]]

Array 2...
[[ 8. inf inf]
[22. 0. 26.]]

Our Array 1 type...
float64

Our Array 2 type...
float64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
2

Our Array 1 Shape...
(2, 3)

Our Array 2 Shape...
(2, 3)

Result (minimum)...
[[ 8. inf 17.]
[22. 0. 0.]]

更新于:2022年2月7日

230 次浏览

启动您的 职业生涯

完成课程后获得认证

开始学习
广告