2

I have a 4-D(d0,d1,d2,d3,d4) numpy array. I want to get a 2-D(d0,d1)mean array, Now my solution is as following:

area=d3*d4
mean = numpy.sum(numpy.sum(data, axis=3), axis=2) / area

But How can I use numpy.mean to get the mean array.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
Samuel
  • 5,977
  • 14
  • 55
  • 77

2 Answers2

4

You can reshape and then perform the average:

res = data.reshape(data.shape[0], data.shape[1], -1).mean(axis=2)

In NumPy 1.7.1 you can pass a tuple to the axis argument:

res = np.mean(data, axis=(2,3,4))
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
0

In at least version 1.7.1, mean supports a tuple of axes for the axis parameter, though this feature isn't documented. I believe this is a case of outdated documentation rather than something you're not supposed to rely on, since similar routines such as sum document the same feature. Nevertheless, use at your own risk:

mean = data.mean(axis=(2, 3))

If you don't want to use undocumented features, you can just make two passes:

mean = data.mean(axis=3).mean(axis=2)
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • But I think your way is a little slower than mine. Beacause you have two time's division right – Samuel Aug 31 '13 at 04:24
  • @Samuel Why don't you use `timeit` and see ;) – tacaswell Aug 31 '13 at 04:28
  • Huh, it does. Neither the 1.7 documentation nor the development version draft documentation say anything about that, and it doesn't look like there's any 1.7.1-specific documentation. – user2357112 Aug 31 '13 at 06:33
  • That's true... they should include this in the documentation since it's such an useful feature... [I opened a ticket in GitHub...](https://github.com/numpy/numpy/issues/3666) – Saullo G. P. Castro Aug 31 '13 at 06:37