Search code examples
numpynumpy-ndarray

Reshape a 3D NumPy array to a 2D array, using the data along axis 2 to upscale


How can I reshape a 3D NumPy array into a 2D array, while utilizing the data along axis 2 to upscale? e.g. 3D array with shape [2,2,4]:

array_3d = [[[ 1  2  3  4]
      [ 5  6  7  8]]
     [[ 9 10 11 12]
      [13 14 15 16]]]

reshape to 2D array with shape [4, 4]:

reshaped_array  =  [[ 1  2 5  6]
      [ 3  4 7  8]
      [ 9 10 13 14]
      [11 12 15 16]]

I've attempted this approach:

reshaped_array = array_3d.swapaxes(1, 2).reshape(-1, array_3d.shape[1])

But I got:

[[ 1  5]
 [ 2  6]
 [ 3  7]
 [ 4  8]
 [ 9 13]
 [10 14]
 [11 15]
 [12 16]]

Solution

  • Assuming this input:

    array = np.arange(1, 17).reshape(2,2,4)
    
    array([[[ 1,  2,  3,  4],
            [ 5,  6,  7,  8]],
    
           [[ 9, 10, 11, 12],
            [13, 14, 15, 16]]])
    

    Reshape to 4D, then swapaxes and back to 3D:

    array.reshape(2, 2, -1, 2).swapaxes(-2, -3).reshape(2, 2, -1)
    
    array([[[ 1,  2,  5,  6],
            [ 3,  4,  7,  8]],
    
           [[ 9, 10, 13, 14],
            [11, 12, 15, 16]]])