w3resource

NumPy: Compute the weighted of a given array


6. Weighted Average of an Array

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.


For more Practice: Solve these Related Problems:

  • Write a function that calculates the weighted average of a 1D array given a separate weight array, ensuring normalization.
  • Create a program that computes the weighted average along a specified axis of a 2D array using np.average with the weights parameter.
  • Implement a solution that handles missing or zero weights by substituting them with default equal weights before averaging.
  • Develop a method to compare the weighted average with the unweighted mean and output the percentage difference.

Go to:


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.

Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.