使用 fmax() 比較兩個 NumPy 陣列並返回元素級最大值


要比較兩個陣列並返回元素級最大值,請在 Python NumPy 中使用 **numpy.fmax()** 方法。返回值為 True 或 False。

比較兩個陣列並返回一個包含元素級最大值的新陣列。如果正在比較的元素之一是 NaN,則返回非 NaN 元素。如果兩個元素都是 NaN,則返回第一個。後一種區別對於複數 NaN 非常重要,複數 NaN 定義為實部或虛部至少有一個是 NaN。其最終效果是在可能的情況下忽略 NaN。

步驟

首先,匯入所需的庫 -

import numpy as np

使用 array() 方法建立兩個 2D NumPy 陣列。我們插入了元素 -

arr1 = np.array([[6, 9, 13],[25, 11, 21]])
arr2 = np.array([[8, 12, 18],[22, 19, 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)

要比較兩個陣列並返回元素級最大值,請在 Python NumPy 中使用 numpy.fmax() 方法。返回值為 True 或 False -

print("
Result (maximum)...
",np.fmax(arr1, arr2))

示例

import numpy as np

# Creating two 2D numpy array using the array() method
# We have inserted elements
arr1 = np.array([[6, 9, 13],[25, 11, 21]])
arr2 = np.array([[8, 12, 18],[22, 19, 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 and return the element-wise maximum, use the numpy.fmax() method in Python Numpy # Return value is either True or False print("
Result (maximum)...
",np.fmax(arr1, arr2))

輸出

Array 1...
[[ 6 9 13]
[25 11 21]]

Array 2...
[[ 8 12 18]
[22 19 26]]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
2

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

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

Result (maximum)...
[[ 8 12 18]
[25 19 26]]

更新於: 2022年2月7日

730 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告