# NumPy mean() – Mean of Array

Contents

## NumPy Mean Function

To calculate mean of elements in a NumPy 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.

## Examples

### 1. Mean of 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 Code Copy

Output

``3.0``

Mean

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

### 2. Mean 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 Code Copy

Output

``[3.5 2.5]``

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.``````

Mean

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

### 3. Mean 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 Code Copy

Output

``[4.  5.5]``

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.``````

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]``````

## Summary

In this NumPy Tutorial, 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.

## Related Tutorials

Code copied to clipboard successfully 👍