返回NumPy中掩碼陣列元素沿軸1的平均值
要返回掩碼陣列元素的平均值,請在 Python NumPy 中使用 **MaskedArray.average()** 方法。“**axis**”引數用於指定沿哪個軸計算平均值。如果為 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() 方法。“axis”引數用於指定沿哪個軸計算平均值。如果為 None,則對扁平化陣列進行平均:
resArr = np.ma.average(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 return the average of the masked array elements, use the MaskedArray.average() method in Python Numpy # The "axis" parameter is used to axis along which to average the array. # If None, averaging is done over the flattened array. resArr = np.ma.average(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 67.33333333333333 62.0 64.5]
廣告