📜  Numpy MaskedArray.average()函数| Python

📅  最后修改于: 2022-05-13 01:54:57.630000             🧑  作者: Mango

Numpy MaskedArray.average()函数| Python

numpy.MaskedArray.average()函数用于返回给定轴上数组的加权平均值。

代码#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