比較兩個包含NaN值的陣列,並使用Numpy返回逐元素最小值


要比較兩個包含一些NaN值的陣列並返回逐元素最小值,請在Python Numpy中使用**numpy.minimum()** 方法。(原文錯誤地使用了maximum())

  • 如果其中一個被比較的元素是NaN,則返回該元素。

  • 如果兩個元素都是NaN,則返回第一個。

  • 後一種區別對於複數NaN很重要,複數NaN定義為實部或虛部至少有一個是NaN。

  • 最終結果是NaN會被傳播。

返回x1和x2的逐元素最小值。如果x1和x2都是標量,則這是一個標量。

比較兩個陣列並返回一個新陣列,該陣列包含逐元素最小值。如果其中一個被比較的元素是NaN,則返回該元素。如果兩個元素都是NaN,則返回第一個。後一種區別對於複數NaN很重要,複數NaN定義為實部或虛部至少有一個是NaN。最終結果是NaN會被傳播。

步驟

首先,匯入所需的庫:

import numpy as np

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

arr1 = np.array([[6, np.nan, np.nan],[25, 11, 0]])
arr2 = np.array([[8, 12, np.nan],[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)

要比較兩個包含NaN值的陣列並返回逐元素最小值,請使用numpy.minimum()方法:

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 nan values
arr1 = np.array([[6, np.nan, np.nan], [25, 11, 0]])
arr2 = np.array([[8, 12, np.nan],[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 NaN values and return the elementwise minimum, use the numpy.maximum() method in Python Numpy # If one of the elements being compared is a NaN, then that element is returned. # If both elements are NaNs then the first is returned. # The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. # The net effect is that NaNs are propagated. print("
Result (minimum)...
",np.minimum(arr1, arr2))

輸出

Array 1...
[[ 6. nan nan]
[25. 11. 0.]]

Array 2...
[[ 8. 12. nan]
[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)...
[[ 6. nan nan]
[22. 0. 0.]]

更新於:2022年2月7日

445 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告