Search code examples
pythonnumpynumpy-ndarraynumpy-slicing

Numpy reshaping from flattened


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]]]])

Solution

  • 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]]])