比較兩個NumPy陣列,並返回忽略NaN的逐元素最小值


要比較兩個陣列並返回忽略NaN的逐元素最小值,請在Python NumPy中使用**numpy.fmin()**方法。返回值為True或False。

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

步驟

首先,匯入所需的庫:

import numpy as np

使用array()方法建立兩個二維NumPy陣列。我們插入了一些包含NaN值的元素:

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

要比較兩個陣列並返回忽略NaN的逐元素最小值,請在Python NumPy中使用numpy.fmin()方法。返回值為True或False:

print("
Result (minimum ignoring NaNs)...
",np.fmin(arr1, arr2))

示例

import numpy as np

# Creating two 2D numpy array using the array() method
# We have inserted elements with some NaN values
arr1 = np.array([[6, 9, np.NaN],[25, 11, 21]])
arr2 = np.array([[8, np.NaN, np.NaN],[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 minimum ignoring NaNs, use the numpy.fmin() method in Python Numpy # Return value is either True or False print("
Result (minimum ignoring NaNs)...
",np.fmin(arr1, arr2))

輸出

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

Array 2...
[[ 8. nan nan]
[22. 19. 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 ignoring NaNs)...
[[ 6. 9. nan]
[22. 11. 21.]]

更新於:2022年2月7日

365 次瀏覽

啟動你的職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.