在 Numpy 中計算沿軸 0 的掩碼陣列元素的中位數


要計算沿特定軸的掩碼陣列元素的中位數,請在 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() 方法建立一個包含 int 元素的陣列

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 = 0)
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 = 0) 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..
. [73.0 33.0 71.5]

更新於: 2022年2月5日

110 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.