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


要計算掩碼陣列元素的中位數,請在 Python Numpy 中使用 **MaskedArray.median()** 方法。

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)

要計算掩碼陣列元素的中位數,請在 Python Numpy 中使用 MaskedArray.median() 方法 -

resArr = np.ma.median(maskArr)
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, use the MaskedArray.median() method in Python Numpy resArr = np.ma.median(maskArr) 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..
. 70.0

更新於: 2022年2月4日

478 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告