比較兩個包含 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))
示例
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))
輸出
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.]]
廣告