w3resource

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:")
print(x)
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:")
print(r1)

Sample Output:

Original array:
[0 1 2 3 4]

Weighted average of the said array:
2.6666666666666665

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

Python: Use Get() to Retrieve a Value in a Dictionary

>>> number_dict = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> number_dict[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 5
>>> number_dict.get(5, 'five')
'five'