Reputation: 1310
For example:
import numpy as np
a = np.array([[[1,2,3],[1,2,3]],[[4,5,6],[7,8,7]]])
print(a.shape)
# (2, 2, 3)
So, on every 2d grid (3 grids on the example above) i want ot compute the mean:
mean = [np.mean(a[:, :, i]) for i in range(3)]
print(mean)
# [3.25, 4.25, 4.75]
Is there a method in numpy that achieves this?
I tried using mean on the axis but the result is not as expected.
Upvotes: 0
Views: 170
Reputation: 32189
You can accomplish this using np.mean(axis = ...)
and specifying a tuple of dimensions to average over
a.mean(axis=tuple(range(len(a.shape) - 1)))
This will compute the mean on every dimension/axis except the last one (note how the range of axis indices goes from 0
up to len - 1
(exclusive) thus ignoring the last axis.
This method is extensible to deeper arrays. For example if you have an array of shape (2, 6, 5, 4, 3)
, it will compute mean as a.mean(axis=(0, 1, 2, 3))
thus giving you an array of 3 means (corresponding to 3 elements in the last dimension)
Upvotes: 1