Open In App

Compute the weighted average of a given NumPy array

Last Updated : 29 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads