Python Numpy MaskedArray.average()函数
numpy.MaskedArray.average()函数用于返回数组在给定轴上的加权平均值。
语法: numpy.ma.average(arr, axis=None, weights=None, returned=False)
参数:
arr : [array_like] 输入屏蔽的数组,其数据要被平均化。屏蔽的条目不会在计算中被考虑到。
axis : [ int, optional] 对Arr进行平均的轴。如果没有,则对扁平化的数组进行平均化。
weights : [array_like, optional] 每个元素在计算平均值时的重要性。如果weights=None,则假设arr中的所有数据的权重都等于1。如果weights是复数,虚数部分将被忽略。
returned : [ bool, optional] 它表示是否应将一个元组(结果,权重之和)作为输出返回(True),或只返回结果(False)。默认是假的。
返回 : [ 标量或MaskedArray] 沿着指定轴的平均值。当返回值为True时,返回一个元组,平均数是第一个元素,权重之和是第二个元素。
代码#1:
# Python program explaining
# numpy.MaskedArray.average() method
# importing numpy as geek
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
# creating input array
in_arr = geek.array([[1, 2], [ 3, -1], [ 5, -3]])
print ("Input array : ", in_arr)
# Now we are creating a masked array.
# by making entry as invalid.
mask_arr = ma.masked_array(in_arr, mask =[[1, 0], [ 1, 0], [ 0, 0]])
print ("Masked array : ", mask_arr)
# applying MaskedArray.average
# methods to masked array
out_arr = ma.average(mask_arr)
print ("normal average of masked array : ", out_arr)
输出:
Input array : [[ 1 2]
[ 3 -1]
[ 5 -3]]
Masked array : [[-- 2]
[-- -1]
[5 -3]]
normal average of masked array : 0.75
代码#2:
# Python program explaining
# numpy.MaskedArray.average() method
# importing numpy as geek
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
# creating input array
in_arr = geek.array([[1, 2], [ 3, -1], [ 5, -3]])
print ("Input array : ", in_arr)
# Now we are creating a masked array.
# by making entry as invalid.
mask_arr = ma.masked_array(in_arr, mask =[[1, 0], [ 1, 0], [ 0, 0]])
print ("Masked array : ", mask_arr)
# applying MaskedArray.average
# methods to masked array
out_arr = ma.average(mask_arr, weights =[[0, 1], [ 0, 2], [ 3, 1]])
print ("weighted average of masked array : ", out_arr)
输出:
Input array : [[ 1 2]
[ 3 -1]
[ 5 -3]]
Masked array : [[-- 2]
[-- -1]
[5 -3]]
weighted average of masked array : 1.7142857142857142