Search code examples
pythonnumpyreshape

Reshape a numpy array so the columns wrap below the original rows


Consider the following scenario:

a = np.array([[1,1,1,3,3,3], [2,2,2,4,4,4]])
np.reshape(a, (4, 3))

Output:

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

Desired output:

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

How can I reshape the array so the rows stay paired together and the overflowing columns wrap below the existing rows? enter image description here


Solution

  • As I described in the comments. You can combine that into one statement:

    import numpy as np
    a = np.array([[1,1,1,3,3,3], [2,2,2,4,4,4]])
    
    a1 = a[:,:3]
    a2 = a[:,3:]
    a3 = np.concatenate((a1,a2))
    print(a3)
    

    Output:

    [[1 1 1]
     [2 2 2]
     [3 3 3]
     [4 4 4]]