Skip to content
Related Articles

Related Articles

Improve Article
Compute the weighted average of a given NumPy array
  • Last Updated : 29 Aug, 2020

In NumPy, we can compute the weighted of a given array by two approaches first approaches is with the help of numpy.average() function in which we pass the weight array in the parameter. And the second approach is by the mathematical computation first we divide the weight array sum from weight array then multiply with the given array to compute the sum of that array.

Method 1: Using  numpy.average() method

Example 1:

Python




import numpy as np
  
  
# Original array
array = np.arange(5)
print(array)
  
weights = np.arange(10, 15)
print(weights)
  
# Weighted average of the given array
res1 = np.average(array, weights=weights)
print(res1)

Output:



[0 1 2 3 4]
[10 11 12 13 14]
2.1666666666666665

Example 2:

Python




import numpy as np
  
  
# Original array
array = np.arange(2, 7)
print(array)
  
weights = np.arange(2, 7)
print(weights)
  
# Weighted average of the given array
res1 = np.average(array, weights=weights)
print(res1)

Output:

[2 3 4 5 6]
[2 3 4 5 6]
4.5

Method 2: Using mathematical operation

Example 1:

Python




import numpy as np
  
  
# Original array
array = np.arange(2, 7)
print(array)
  
weights = np.arange(2, 7)
print(weights)
  
# Weighted average of the given array
res2 = (array*(weights/weights.sum())).sum()
print(res2)

Output:

[2 3 4 5 6]
[2 3 4 5 6]
4.5

Example 2:

Python




import numpy as np
  
  
# Original array
array = np.arange(5)
print(array)
  
weights = np.arange(10, 15)
print(weights)
  
# Weighted average of the given array
res2 = (array*(weights/weights.sum())).sum()
print(res2)

Output:

[0 1 2 3 4]
[10 11 12 13 14]
2.166666666666667

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :