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:
# Importing the NumPy library
import numpy as np
# Creating an array 'x' using arange with 5 elements
x = np.arange(5)
# Displaying the original array 'x'
print("\nOriginal array:")
print(x)
# Creating weights from 1 to 5 using arange
weights = np.arange(1, 6)
# Calculating the weighted average of the array 'x' using np.average() and 'weights'
r1 = np.average(x, weights=weights)
# Calculating the weighted average manually
r2 = (x * (weights / weights.sum())).sum()
# Asserting if the results from np.average() and manual calculation are close
assert np.allclose(r1, r2)
# Displaying the calculated weighted average of the array 'x'
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
Explanation:
In the above code –
x = np.arange(5): An array x is created using the numpy.arange function to generate the values [0, 1, 2, 3, 4].
weights = np.arange(1, 6): Here numpy.arange generates the values [1, 2, 3, 4, 5], which will be used as the weights for the weighted average calculation.
r1 = np.average(x, weights=weights): The numpy.average function is then used to calculate the weighted average of x using the weights array. The resulting value is assigned to r1.
r2 = (x*(weights/weights.sum())).sum(): This code calculates the weighted average manually using the formula r2 = (x*(weights/weights.sum())).sum().
assert np.allclose(r1, r2): Finally, the code uses the numpy.allclose function to assert that r1 and r2 are equal within a tolerance. It returns true as r1 and r2 are equal.
Python-Numpy 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 Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-stat-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics