Mean of NxM elements of array

Viewed 85

I want to average each NxM elements in the AxB array and that the dimension of the output matrix to be ​​(A/N)x(B/M).

For example, let us suppose that I have:

a = np.arange(24).reshape((4,6))

array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])

I want to average each 2x3 elements of "a" array and that the output to be:

array([[av1, av2],
       [av3, av4]])

where:

av1 = (0+1+2+6+7+8)/6

av2 = (3+4+5+9+10+11)/6

av3 = (12+13+14+18+19+20)/6

av4 = (15+16+17+21+22+23)/6

What is the most efficient method to do that in python? I want to do that with an array of 5424x5424 elements.

1 Answers

As of version 1.7, np.mean accepts multiple axes to average. This makes your task easier because you can create as many extra dimensions as you need and process all of them without having to do any extra work.

 np.mean(a.reshape(2, 2, 2, 3), axis=(1, 3))
Related