NumPy: Compute the weighted of a given array

NumPy Statistics: Exercise-6 with Solution

Write a NumPy program to compute the weighted of a given array.

Sample Solution:-

Python Code:

import numpy as np
x = np.arange(5)
print("\nOriginal array:")
weights = np.arange(1, 6)
r1 = np.average(x, weights=weights)
r2 = (x*(weights/weights.sum())).sum()
assert np.allclose(r1, r2)
print("\nWeighted average of the said array:")

Sample Output:

Original array:
[0 1 2 3 4]

Weighted average of the said array:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to compute the median of flattened given array.
Next: Write a NumPy program to compute the mean, standard deviation, and variance of a given array along the second axis.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

Python: Tips of the Day

Chain Operators

You can chain comparison operators in Python as following: n = 10 result = 1 < n < 20

distance = 200
checker = 100 < distance < 350