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

Time:12-13

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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