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

Question:

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

Asked By: imbrizi

||

Answers:

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]]
Answered By: Tim Roberts

Yet another option:

import numpy as np

a = np.hstack(a.T.reshape(2,3,2)).T

print(a)

Output:

array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4]])
Answered By: lemon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.