返回NumPy中掩碼陣列元素的平均值


要返回掩碼陣列元素的平均值,請在Python NumPy中使用**MaskedArray.average()**方法。axis引數是沿其計算a的平均值的軸。如果為None,則在扁平化陣列上進行平均。

weights引數表示每個元素在平均值計算中的重要性。weights陣列可以是一維的,也可以與a的形狀相同。如果weights=None,則假設a中的所有資料權重都等於1。一維計算為:

avg = sum(a * weights) / sum(weights)

該函式返回沿指定軸的平均值。當returned為True時,返回一個元組,其中平均值作為第一個元素,權重總和作為第二個元素。如果a為整數型別且浮點數小於float64,則返回型別為np.float64;否則為輸入資料型別。如果返回,sum_of_weights始終為float64。

步驟

首先,匯入所需的庫:

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.average()方法:

resArr = np.ma.average(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 return the average of the masked array elements, use the MaskedArray.average() method in Python Numpy resArr = np.ma.average(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..
. 67.0

更新於:2022年2月4日

792 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告