How to calculate the mean along a given axis with numpy in python ?

September 19, 2021    /    Viewed: 188    /    Comments: 0    /    Edit


Examples of how to calculate the mean along a given axis with numpy in python

Create a random matrix with numpy

import numpy as np

data = np.random.randint(0,10,size=(3,3))

gives for exaple

array([[4, 1, 9],
       [1, 6, 5],
       [9, 9, 5]])

Calculate the mean along an axis with numpy

To calculate the mean along an axis with numpy, a solution is to use numpy.mean, example along axis=0

data.mean(axis=0)

gives

array([4.66666667, 5.33333333, 6.33333333])

Note: to round alement of a matrix with numpy a solution is to use numpy.matrix.round

np.round( data.mean(axis=0) , 2)

gives then

array([4.67, 5.33, 6.33])

Note: same as doing

data.sum(axis=0) / data.shape[0]

gives

array([4.66666667, 5.33333333, 6.33333333])

Another example along axis=1:

data.mean(axis=1)

gives

array([4.66666667, 4.        , 7.66666667])

and

np.round( data.mean(axis=1) , 2)

gives

array([4.67, 4.  , 7.67])

Note: same as doing

data.sum(axis=1) / data.shape[1]

gives

array([4.66666667, 4.        , 7.66666667])

Calculate the mean using all elements of a matrix

data.mean()

gives

5.444444444444445

Note: same as doing

data.sum() / data.size

also returns

5.444444444444445

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!