Home > Blockchain >  Numpy - Reshape 2d array and keep order
Numpy - Reshape 2d array and keep order

Time:04-26

I have an array of 64 numbers arranged in an 8x8 using x = np.arange(64).reshape(8, 8) which i would like to reshape to be a 4x4 array with 2x2 sub arrays. I.e. this original array should become this.

Simply reshaping the array using x = x.reshape(4,4,2,2) results in this outcome

How do i overcome this?

Thanks

CodePudding user response:

You need to do a little rearranging of the axes to match your expected outcome. In this case you've split each 8-length side into 4 blocks of 2, but then want the blocks of 2 in the final dimensions. So:

np.arange(64).reshape(4,2,4,2).transpose(0,2,1,3)
Out[]: 
array([[[[ 0,  1],
         [ 8,  9]],

        [[ 2,  3],
         [10, 11]],

        [[ 4,  5],
         [12, 13]],

        [[ 6,  7],
         [14, 15]]],


       [[[16, 17],
         [24, 25]],

        [[18, 19],
         [26, 27]],

        [[20, 21],
         [28, 29]],

        [[22, 23],
         [30, 31]]],


       [[[32, 33],
         [40, 41]],

        [[34, 35],
         [42, 43]],

        [[36, 37],
         [44, 45]],

        [[38, 39],
         [46, 47]]],


       [[[48, 49],
         [56, 57]],

        [[50, 51],
         [58, 59]],

        [[52, 53],
         [60, 61]],

        [[54, 55],
         [62, 63]]]])

CodePudding user response:

Another way could be using the sliding_window:

y = np.lib.stride_tricks.sliding_window_view(x, (2,2))[::2, ::2]
y
array([[[[ 0,  1],
         [ 8,  9]],

        [[ 2,  3],
         [10, 11]],

        [[ 4,  5],
         [12, 13]],

        [[ 6,  7],
         [14, 15]]],


       [[[16, 17],
         [24, 25]],
  • Related