NumPy - average() function
The NumPy average() function is used to compute the weighted average along the specified axis. The syntax for using this function is given below:
Syntax
numpy.average(a, axis=None, weights=None, returned=False)
Parameters
a |
Required. Specify an array containing data to be averaged. If a is not an array, a conversion is attempted. |
axis |
Optional. Specify axis or axes along which to average a. The default, axis=None, will average over all of the elements of the input array. If axis is negative it counts from the last to the first axis. |
weight |
Optional. Specify an array of weights associated with the values in a. The weights array can either be 1-D (in which case its length must be the size of a along the given axis) or of the same shape as a. If weights=None, then all data in a are assumed to have a weight equal to one. |
returned |
Optional. Default is False. If True, the tuple (average, sum_of_weights) is returned, otherwise only the average is returned. |
Return Value
Returns the average along the specified axis when returned is False. When returned is set to True, returns a tuple with the average as the first element and the sum of the weights as the second element.
Exception
- Raises ZeroDivisionError exception, When all weights along axis are zero.
- Raises TypeError exception, When the length of 1D weights is not the same as the shape of a along axis.
Example: Average of all values
In the example below, average() function is used to calculate average of all values present in the array.
import numpy as np Arr = np.array([[1,2],[3, 4]]) print("Array is:") print(Arr) #average of all values print("\nAverage of values:", np.average(Arr))
The output of the above code will be:
Array is: [[1 2] [3 4]] Average of values: 2.5
Example: average() with axis parameter
When axis parameter is provided, averaging is performed over the specified axes. Consider the following example.
import numpy as np Arr = np.array([[10,20,30],[70,80,90]]) print("Array is:") print(Arr) #averaging along axis=0 print("\nAverage along axis=0") print(np.average(Arr, axis=0)) #averaging along axis=1 print("\nAverage along axis=1") print(np.average(Arr, axis=1))
The output of the above code will be:
Array is: [[10 20 30] [70 80 90]] Average along axis=0 [40. 50. 60.] Average along axis=1 [20. 80.]
Example: average() with weight parameter
In the example below, weight array is provided to calculate weighted average along the specified axis.
import numpy as np Arr = np.array([[10,20],[80,90]]) w = np.array([0.4, 0.6]) print("Array is:") print(Arr) #averaging along axis=0 print("\nWeighted Average along axis=0") print(np.average(Arr, axis=0, weights=w)) #averaging along axis=1 print("\nWeighted Average along axis=1") print(np.average(Arr, axis=1, weights=w))
The output of the above code will be:
Array is: [[10 20] [80 90]] Weighted Average along axis=0 [52. 62.] Weighted Average along axis=1 [16. 86.]
❮ NumPy - Functions