Python Numpy – Array Average – average()

Numpy Average

Using Numpy, you can calculate average of elements of total Numpy Array, or along some axis, or you can also calculate weighted average of elements.

To find the average of an numpy array, you can use numpy.average() statistical function.

Syntax – Numpy average()

The syntax of average() function is as shown in the following.

numpy.average(a, axis=None, weights=None, returned=False)
Run

We shall learn more about the parameters specified in the above syntax, with the help of following examples.

Example 1: Numpy Average

In this example, we take a 2×2 array with numbers and find the average of the array using average() function.

Python Program

import numpy as np

a = np.array([4, 5, 3, 7]).reshape(2,2)
print('input\n',a)

b = np.average(a)
print('average\n',b)
Run

Output

input
 [[4 5]
 [3 7]]
average
 4.75

Example 2: Numpy average() along Axis

You can also find the average of an array along axis.

In this example, we will specify the axis of interest using axis parameter.

Python Program

import numpy as np

a = np.array([4, 5, 3, 7]).reshape(2,2)
print('input\n',a)

b = np.average(a, axis=0)
print('average along axis=0\n',b)

b = np.average(a, axis=1)
print('average along axis=1\n',b)
Run

Output

input
 [[4 5]
 [3 7]]
average along axis=0
 [3.5 6. ]
average along axis=1
 [4.5 5. ]

Example 3: Numpy average() with weights

You can also specify weights while calculating the average of elements in array. These weights will be multiplied with the elements and then the average of the resulting is calculated.

Python Program

import numpy as np

a = np.array([4, 5, 3, 7]).reshape(2,2)
print('input\n',a)

b = np.average(a, axis=0, weights=[0.3,0.7])
print('average along axis=0\n',b)

b = np.average(a, axis=0, weights=[0.2,0.8])
print('average along axis=1\n',b)
Run

Output

input
 [[4 5]
 [3 7]]
average along axis=0
 [3.3 6.4]
average along axis=1
 [3.2 6.6]

Summary

In this Numpy Tutorial of Python Examples, we learned how to calculate average of numpy array elements using numpy.average() function.