numpy.average() in Python
The numpy module of Python provides a function called numpy.average(), used for calculating the weighted average along the specified axis.
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.
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.
This error is raised when all weights along the axis are set to zero.
This error is raised when the length of the weighted array is not the same as the shape of the input array.
[1, 2, 3, 4, 5] 3.0
In the above code:
In the output, it shows the average of the list elements.
array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) array([ 1.44444444, 4.44444444, 7.44444444, 10.44444444])
In the above code:
In the output, it shows the average of each column elements in the array.
array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 406, in average "Axis must be specified when shapes of data and weights." TypeError: Axis must be specified when shapes of data and weights differ.
Note: The output shows a type error: 'Axis must be specified when shapes of data and weights differ' because the shape of the 'weights' array is not the same as the input array 'data'.