Home > OS >  Build an array with size (1,n) from an array with size (m, k) with a smarter way
Build an array with size (1,n) from an array with size (m, k) with a smarter way

Time:12-13

I have a very large array with size (5, n), I want to build an array with size (1,20) from it in each iteration. I have to use a very basic approach to build my new array. Here is an example:

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

I want to build an array with size (1,20) from A. Which 0-4 is from row 0 of A, 4-8 from row 1 of A, 8-12 from row 2 A, and 12-16 from row 3, and 16-20 from row 4`. I use this code:

B = np.zeros((1, 20))
B[0, 0:4] =  A[0, 0:4]
B[0, 4:8] =  A[1, 0:4]
B[0, 8:12] =  A[2, 0:4]
B[0, 12:16] =  A[3, 0:4]
B[0, 16:20] =  A[4, 0:4]

and my B is :

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

However, since I have a lot of this type of array in my code, I want to ask, do you have any solution which does not to need to use all of this lines of code for it? Thank you.

CodePudding user response:

It seems you just want to slice the first four columns of A and flatten them row-wise:

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

B = A[:, 0:4].flatten()

Which gives the desired value of B, but with a shape (N, ).

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

Since you want your resulting array to have shape (1, N), you can just reshape it to that shape instead of flattening:

B = A[:, 0:4].reshape((1, -1))
# array([[4, 2, 1, 4, 4, 2, 0, 3, 3, 2, 3, 2, 1, 1, 1, 3, 3, 3, 4, 1]])

Reshaping to a shape of (1, -1) reshapes it to 1 row, and -1 (i.e. as many as required) columns.

  • Related