在 NumPy 中計算掩碼陣列元素沿軸 1 的最大值
要計算給定**軸**上掩碼陣列元素的最大值,請在 Python NumPy 中使用**MaskedArray.max()**方法。軸使用“axis”引數設定。軸是操作的軸。
max() 函式返回一個包含結果的新陣列。如果指定了 out,則返回 out。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”引數設定。軸是操作的軸 -
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]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP