codemaniac codemaniac - 27 days ago 7
Python Question

Reshape numpy array to contain logical blocks of values from original array

My google-fu has failed me!

I have a numpy array as follows:

0 1 2 3
------------------------
0 | 100 110 120 130
1 | 140 150 160 170
2 | 180 190 200 210
3 | 220 230 240 250
4 | 260 270 280 290
5 | 300 310 320 330
6 | 340 350 360 370
7 | 380 390 400 410
8 | 420 430 440 450


The shape of which is
(9, 4)
. I want to reshape the above array to the following
(6, 6)
array:

0 1 2 3 4 5
-------------------------------------
0 | 100 110 | 140 150 | 180 190
1 | 120 130 | 160 170 | 200 210
-------------------------------------
2 | 220 230 | 260 270 | 300 310
3 | 240 250 | 280 290 | 320 330
-------------------------------------
4 | 340 350 | 380 390 | 420 430
5 | 360 370 | 400 410 | 440 450


I'm able to do it with 2
for
loops and some conditions. Is there a better way to achieve the same result using
numpy.reshape
in a single line of code?

Thanks in advance.

Answer

Actually it is a (3, 3) array of (2, 2) arrays, so a (3, 3, 2, 2) array:

a.reshape(3, 3, 2, 2)