Build array with size (n*k, m) with n matrix of size (k,m) with an efficient way

Question:

I have three array (A,B,C) with size (2,4) and I want to build an array (X) with size (2*3, 4) with them.
I want to build the first row of X from A, the second from B, and the third from C. Then, fourth row from A, 5 from B, 6 from C.

import numpy as np

A = np.array([[0, 2, 1, 2],
       [3, 1, 4, 3]])
B = np.array([[1, 2, 1, 0],
       [0, 4, 3, 1]])
C = np.array([[0, 4, 3, 2],
   [3, 0, 1, 0]])

Now, the way that I am doing this is using a loop over the arrays. But, it is not efficient. Do you have any suggestion? Thank you.

The way that I am doing is:

X = np.zeros((2*3, 4))
for i in range(2):
    X[3*i] = A[i,:]
    X[3*i+1] = B[i,:]
    X[3*i+2] = C[i,:]
X
array([[0., 2., 1., 2.],
   [1., 2., 1., 0.],
   [0., 4., 3., 2.],
   [3., 1., 4., 3.],
   [0., 4., 3., 1.],
   [3., 0., 1., 0.]])

Also, some times I have 5, 6 array and I should build the X with size (6*2, 4). So, with this way, I have to add or remove some lines of code to work. I am looking for a general and efficient way. Thank you.

Asked By: sadcow

||

Answers:

A possible solution:

np.reshape(np.hstack((A, B, C)), (6, 4))

Output:

array([[0, 2, 1, 2],
       [1, 2, 1, 0],
       [0, 1, 0, 0],
       [3, 1, 4, 3],
       [0, 4, 3, 1],
       [4, 4, 3, 4]])
Answered By: PaulS

So, your output doesn’t really match your description (e.g., the third row is not from C, the last row didn’t get filled in with any rows from the original arrays). But going off of the description, you could do something like:

import numpy as np

A = np.array([[0, 2, 1, 2],
       [3, 1, 4, 3]])
B = np.array([[1, 2, 1, 0],
       [0, 4, 3, 1]])
C = np.array([[0, 1, 0, 0],
       [4, 4, 3, 4]])

arr = np.concatenate([A[:, None], B[:, None], C[:,None]], axis=1)

arr.shape = (6, -1)
print(arr)

Which gives:

[[0 2 1 2]
 [1 2 1 0]
 [0 1 0 0]
 [3 1 4 3]
 [0 4 3 1]
 [4 4 3 4]]
Answered By: juanpa.arrivillaga

Simply with combination numpy.stack + numpy.concatenate functions:

In [296]: np.concatenate(np.stack((A,B,C), axis=1))
Out[296]: 
array([[0, 2, 1, 2],
       [1, 2, 1, 0],
       [0, 1, 0, 0],
       [3, 1, 4, 3],
       [0, 4, 3, 1],
       [4, 4, 3, 4]])
Answered By: RomanPerekhrest
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.