NumPy mean() – Mean of Numpy Array

NumPy Mean

NumPy Mean: To calculate mean of elements in a array, as a whole, or along an axis, or multiple axis, use numpy.mean() function.

In this tutorial we will go through following examples using numpy mean() function.

• Mean of all the elements in a NumPy Array.
• Mean of elements of NumPy Array along an axis.
• Mean of elements of NumPy Array along multiple axis.

Example 1: Mean of all the elements in a NumPy Array

In this example, we take a 2D NumPy Array and compute the mean of the Array.

Python Program

import numpy as np

#initialize array
A = np.array([[2, 1], [5, 4]])

#compute mean
output = np.mean(A)

print(output)
Run

Output

3.0
Run

Mean

Mean = (2 + 1 + 5 + 4)/4
= 12/4
= 3.0
Run

Example 2: Mean of elements of NumPy Array along an axis

In this example, we take a 2D NumPy Array and compute the mean of the elements along a single, say axis=0.

Pass the named argument axis to mean() function as shown below.

Python Program

import numpy as np

#initialize array
A = np.array([[2, 1], [5, 4]])

#compute mean
output = np.mean(A, axis=0)

print(output)
Run

Output

[3.5 2.5]
Run

Understanding Axis

As we have provided axis=0 as argument, this axis gets reduced to compute mean along this axis, keeping other axis.

[    [2, 1],  [5, 4]   ]
axis:  0    1        1

[2, 1] and [5, 4] are the elements of axis=0.
Run

Mean

Mean = ([2, 1] + [5, 4])/2
= [(2 + 5)/2, (1 + 4)/2]
= [7/2, 5/2]
= [3.5, 2.5]
Run

Example 3: Mean of elements of NumPy Array along Multiple Axis

In this example, we take a 3D NumPy Array, so that we can give atleast two axis, and compute the mean of the Array.

Pass the named argument axis, with tuple of axes, to mean() function as shown below.

Python Program

import numpy as np

#initialize array
A = np.array([[[2, 1], [5, 4]], [[3, 9], [6, 8]]])

#compute mean
output = np.mean(A, axis=(0, 1))

print(output)
Run

Output

[4.  5.5]
Run

Understanding Axis

As we have provided axis=(01 1) as argument, these axis gets reduced to compute mean along this axis, keeping other axis. which is axis: 2.

[    [  [2, 1], [5, 4]], [  [3, 9], [6, 8] ]  ]
axis:  0    1  2       2        1  2       2

[[2, 1], [5, 4]] and [[3, 9], [6, 8]] are the elements of axis=0.
[2, 1], [5, 4], [3, 9], [6, 8] are the elements of axis=1.
Run

Mean

Mean = ([2, 1] + [5, 4] + [3, 9] + [6, 8])/4
= [(2 + 5 + 3 + 6)/4, (1 + 4 + 9 + 8)/4]
= [4.0, 5.5]
Run

Summary

In this tutorial of Python Examples, we learned how to find mean of a Numpy, of a whole array, along an axis, or along multiple axis, with the help of well detailed Python example programs.