The numpy module of Python provides a function called numpy.average(), used for calculating the weighted average along the specified axis.
numpy.average(a, axis=None, weights=None, returned=False)
x: array_like
This parameter defines the source array whose element's average we want to calculate. The conversion will be attempted if 'x' is an array.
axis: int or None or tuple of ints(optional)
This parameter defines the axis along which the average is going to be calculated. By default, the axis is set to None, which will calculate the average of all the elements of the source array. Counts start from the ending to the starting axis when the value of the axis is negative.
weights : array_like(optional)
This parameter defines an array containing weights associated with the array values. Each value of array elements together makes the average according to its associated weight. The weighted array can be one-dimensional or of the same shape as the input array. When there is no weight associated with the array element, the weight will be treated as 1 for all elements.
returned: bool(optional)
By default, this parameter is set to False. If we set it as True, then a tuple of average and sum_of_weights, is returned. If it is False, the average is returned. The weighted sum is equivalent to the number of elements if there are no values for weights.
retval, [sum_of_weights]: array_type or double
This function returns either the average or both the average and the sum_of_weights that depend on the returned parameter.
ZeroDivisionError
This error is raised when all weights along the axis are set to zero.
TypeError
This error is raised when the length of the weighted array is not the same as the shape of the input array.
import numpy as np data = list(range(1,6)) output=np.average(data) data output
Output:
In the above code:
In the output, it shows the average of the list elements.
import numpy as np output=np.average(range(1,16), weights=range(15,0,-1)) output
Output:
import numpy as np data=np.arange(12).reshape((4,3)) output = np.average(data, axis=1, weights=[1./4, 3./4, 5./4]) data output
Output:
In the above code:
In the output, it shows the average of each column elements in the array.
import numpy as np data=np.arange(12).reshape((4,3)) data np.average(data, weights=[1./4, 3./4, 5./4])
Output: