0

Some code results in the numpy array: array([[2, 2, 1, 0, 4, 2, 3, 3]])

From which, I want to recover:

array([ [[2, 1], 
         [4, 3]], 

         [[2, 0], 
          [2, 3]] ])

ie: place skipping elements into two matrices.

Please advise on how this can be achieved for arbitrary number of final matrices (2 in toy example) and their dimensions (always equal to one another; 2x2 in toy example).

I tried and failed with reshape(2,2,2,1) which results in:

array([[[[2],
         [2]],

        [[1],
         [0]]],


       [[[4],
         [2]],

        [[3],
         [3]]]])
maplemilk
  • 70
  • 1
  • 6
  • You need to include a transpose/swapaxes, `reshape` is not enough. `reshape` to (2,2,2), and then try various transpose to put the axes in the desired order. – hpaulj Apr 20 '23 at 00:43

1 Answers1

1
In [195]: arr = np.array([[2, 2, 1, 0, 4, 2, 3, 3]])

In [196]: arr.reshape(2,2,2)
Out[196]: 
array([[[2, 2],
        [1, 0]],

       [[4, 2],
        [3, 3]]])

first guess on transpose -

In [197]: arr.reshape(2,2,2).transpose(2,1,0)
Out[197]: 
array([[[2, 4],
        [1, 3]],

       [[2, 2],
        [0, 3]]])

not quite, switching the last 2 dimensions correct that:

In [198]: arr.reshape(2,2,2).transpose(2,0,1)
Out[198]: 
array([[[2, 1],
        [4, 3]],

       [[2, 0],
        [2, 3]]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353