How to get a middle array with numpy

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

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

But how can I use numpy.mean to get the middle array.

+2
source share
2 answers

You can change the shape and then do 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)) 
+4
source

In the version at least version 1.7.1, mean supports a tuple of axes for the axis parameter, although this function is not documented. I believe this is an example of outdated documentation, and not something you should not rely on, since similar procedures, such as sum , document the same function. However, use at your own risk:

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

If you do not want to use undocumented functions, you can simply do two passes:

 mean = data.mean(axis=3).mean(axis=2) 
0
source

All Articles