使用Numpy計算掩碼陣列沿指定軸的最大值
要計算掩碼陣列沿指定軸的最大值,可以使用Python Numpy中的**MaskedArray.max()**方法。該函式**max()**返回一個包含結果的新陣列。如果指定了out,則返回out。軸使用“axis”引數設定。“axis”引數指定操作的軸。
out引數是用於放置結果的備用輸出陣列。必須與預期輸出具有相同的形狀和緩衝區長度。fill_value是用於填充掩碼值的數值。如果為None,則使用maximum_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.max()方法。軸使用“axis”引數設定。“axis”引數指定操作的軸:
resArr = maskArr.max(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 maximum of the masked array elements along a given axis, use the MaskedArray.max() method in Python Numpy
# The axis is set using the "axis" parameter
# The axis is the axis along which to operate
resArr = maskArr.max(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 93 73 67]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP