numpy.average() in Python | np.average() in Python

Numpy average() is used to calculate the weighted average along the specified axis.

Syntax of Numpy average()

np.average(arr, axis=None, weights=None)

Here arr refers to the array whose weighted average is to be calculated.

axis parameter is optional and is used to specify the axis along which we want to perform a weighted average. When no axis value is passed then a weighted average of entire values is computed and a single value is returned.

weights parameter is optional and is used to specify the weight for the values present in arr. When no value is passed for weights parameter then the weight is considered to be one for each value. weights parameter takes the value in the form of Numpy array or list.

Example 1: When weights parameter is not used

import numpy as np

x = np.array([32, 4, 8, 12, 20])
print('Average of arr x:', np.average(x))
y = np.array([[32, 4, 8, 12, 20], [35, 5, 15, 10, 30]])
print('Average of arr y:', np.average(y))

Output of the above program

Average of arr x: 15.2
Average of arr y: 17.1

Example 2: When weights parameter is used

import numpy as np

x = np.array([32, 4, 8, 12, 20])
print('Average of arr x:', np.average(x, weights=[1, 2, 3, 4, 5]))
y = np.array([[32, 4, 8, 12, 20], [35, 5, 15, 10, 30]])
print('Average of arr y along axis0:', np.average(y, axis=0, weights=[0, 1]))
print('Average of arr y along axis1:', np.average(y, axis=1, weights=[0.2, 1.2, 0.5, 0.32, 2.5]))

Output of the above program

Average of arr x: 14.133
Average of arr y along axis0: [35.  5. 15. 10. 30.]
Average of arr y along axis1: [14.627 20.911]

Recommended Posts