返回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
广告