使用Numpy計算掩碼陣列沿軸1的最小值


要計算沿給定軸的掩碼陣列元素的最小值,請使用Python Numpy中的**MaskedArray.min()**方法:

  • 軸使用“axis”引數設定。
  • 軸是操作的軸。

min()函式返回一個包含結果的新陣列。如果指定了out,則返回out。out引數是放置結果的備用輸出陣列。必須與預期輸出具有相同的形狀和緩衝區長度。fill_value是用於填充掩碼值的數值。如果為None,則使用minimum_fill_value()的輸出。如果keepdims設定為True,則減少的軸將作為大小為一的維度保留在結果中。使用此選項,結果將正確地對陣列進行廣播。

步驟

首先,匯入所需的庫:

import numpy as np
import numpy.ma as ma

使用numpy.array()方法建立一個包含整數元素的陣列:

arr = np.array([[65, 68, 81], [93, 33, 76], [73, 88, 51], [62, 45, 67]])
print("Array...
", arr)

建立一個掩碼陣列並將其中一些標記為無效:

maskArr = ma.masked_array(arr, mask =[[1, 1, 0], [ 0, 0, 0], [0, 1, 0], [0, 1, 0]])
print("
Our Masked Array...
", maskArr)

獲取掩碼陣列的型別:

print("
Our Masked Array type...
", maskArr.dtype)

獲取掩碼陣列的維度:

print("
Our Masked Array Dimensions...
",maskArr.ndim)

獲取掩碼陣列的形狀:

print("
Our Masked Array Shape...
",maskArr.shape)

獲取掩碼陣列的元素個數:

print("
Number of elements in the Masked Array...
",maskArr.size)

要計算沿給定軸的掩碼陣列元素的最小值,請使用MaskedArray.min()方法。軸使用“axis”引數設定。軸是操作的軸:

resArr = maskArr.min(axis = 1)
print("
Resultant Array..
.", resArr)

示例

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[65, 68, 81], [93, 33, 76], [73, 88, 51], [62, 45, 67]])
print("Array...
", arr) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[[1, 1, 0], [ 0, 0, 0], [0, 1, 0], [0, 1, 0]]) print("
Our Masked Array...
", maskArr) # Get the type of the masked array print("
Our Masked Array type...
", maskArr.dtype) # Get the dimensions of the Masked Array print("
Our Masked Array Dimensions...
",maskArr.ndim) # Get the shape of the Masked Array print("
Our Masked Array Shape...
",maskArr.shape) # Get the number of elements of the Masked Array print("
Number of elements in the Masked Array...
",maskArr.size) # To compute the minimum of the masked array elements along a given axis, use the MaskedArray.min() method in Python Numpy # The axis is set using the "axis" parameter # The axis is the axis along which to operate resArr = maskArr.min(axis = 1) print("
Resultant Array..
.", resArr)

輸出

Array...
[[65 68 81]
[93 33 76]
[73 88 51]
[62 45 67]]

Our Masked Array...
[[-- -- 81]
[93 33 76]
[73 -- 51]
[62 -- 67]]

Our Masked Array type...
int64

Our Masked Array Dimensions...
2

Our Masked Array Shape...
(4, 3)

Number of elements in the Masked Array...
12

Resultant Array..
. [81 33 51 62]

更新於:2022年2月5日

232 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告