Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get mean of 2D slice of a 3D array in numpy

Tags:

I have a numpy array with a shape of:

(11L, 5L, 5L)

I want to calculate the mean over the 25 elements of each 'slice' of the array [0, :, :], [1, :, :] etc, returning 11 values.

It seems silly, but I can't work out how to do this. I've thought the mean(axis=x) function would do this, but I've tried all possible combinations of axis and none of them give me the result I want.

I can obviously do this using a for loop and slicing, but surely there is a better way?

like image 644
robintw Avatar asked Aug 21 '13 12:08

robintw


People also ask

How do you find the mean of a 2D array in Python?

To calculate the average of all values in a two-dimensional NumPy array called matrix , use the np. average(matrix) function. This calculates the average of the flattened out matrix, i.e., it's the same as calling np. average([1, 0, 2, 1, 1, 1]) without the two-dimensional structuring of the data.

How do you access the elements of a 2D NumPy array?

Indexing a Two-dimensional Array To access elements in this array, use two indices. One for the row and the other for the column. Note that both the column and the row indices start with 0. So if I need to access the value '10,' use the index '3' for the row and index '1' for the column.

How do you access elements in a multidimensional array in Python?

In Python, we can access elements of a two-dimensional array using two indices. The first index refers to the indexing of the list and the second index refers to the position of the elements. If we define only one index with an array name, it returns all the elements of 2-dimensional stored in the array.


2 Answers

Use a tuple for axis :

>>> a = np.arange(11*5*5).reshape(11,5,5)
>>> a.mean(axis=(1,2))
array([  12.,   37.,   62.,   87.,  112.,  137.,  162.,  187.,  212.,
        237.,  262.])

Edit: This works only with numpy version 1.7+.

like image 110
J. Martinot-Lagarde Avatar answered Sep 25 '22 06:09

J. Martinot-Lagarde


You can reshape(11, 25) and then call mean only once (faster):

a.reshape(11, 25).mean(axis=1)

Alternatively, you can call np.mean twice (about 2X slower on my computer):

a.mean(axis=2).mean(axis=1)
like image 30
Saullo G. P. Castro Avatar answered Sep 22 '22 06:09

Saullo G. P. Castro