2

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.

joaohenry23
  • 145
  • 5

1 Answers1

0

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))
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • Thank you for your answer, it help me alot. I only modified some numbers and I got the result that I wanted: a.reshape((2,2,2,3)).mean(axis=(1,3)) array([[ 4., 7.], [16., 19.]]) – joaohenry23 Oct 22 '19 at 17:55
  • @joaohenry23. Please do not make substantial edits to answers other than your own. – Mad Physicist Oct 23 '19 at 00:05