在 Numpy 中計算沿指定軸的掩碼陣列元素的中位數
要計算沿特定軸的掩碼陣列元素的中位數,請在 Python Numpy 中使用 **MaskedArray.median()** 方法 -
- 軸使用“axis”引數設定
- 軸是計算中位數的軸。
- 預設值(None)是沿陣列的扁平化版本計算中位數。
overwrite_input 引數如果為 True,則允許使用輸入陣列 (a) 的記憶體進行計算。輸入陣列將被對 median 的呼叫修改。當您不需要保留輸入陣列的內容時,這將節省記憶體。將輸入視為未定義,但它可能會被完全或部分排序。預設為 False。請注意,如果 overwrite_input 為 True,並且輸入不是 ndarray,則會引發錯誤。
步驟
首先,匯入所需的庫 -
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.median() 方法。軸使用“axis”引數設定。軸是計算中位數的軸。預設值(None)是沿陣列的扁平化版本計算中位數 -
resArr = np.ma.median(maskArr, 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 median of the masked array elements along specific axis, use the MaskedArray.median() method in Python Numpy
# The axis is set using the "axis" parameter
# The axis is axis along which the medians are computed.
# The default (None) is to compute the median along a flattened version of the array.
resArr = np.ma.median(maskArr, 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.0 76.0 62.0 64.5]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP