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?
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.
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.
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.
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+.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With