How do I stack arrays horizontally?

81 views Asked by At

I have an array:

> a
array([[[1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]],
       [[17, 18, 19, 20], 
        [21, 22, 23, 24], 
        [25, 26, 27, 28], 
        [29, 30, 31, 32]]])

How can I reshape that to this:

[[1, 2, 3, 4, 17, 18, 19, 20],
 [5, 6, 7, 8, 21, 22, 23, 24],
 [9, 10, 11, 12, 25, 26, 27, 28],
 [13, 14, 15, 16, 29, 30, 31, 32]]

I have tried the reshape function, but it returns this:

[[1, 2, 3, 4, 5, 6, 7, 8],
 [9, 10, 11, 12, 13, 14, 15, 16],
 [17, 18, 19, 20, 21, 22, 23, 24],
 [25, 26, 27, 28, 29, 30, 31, 32]]

Is there any solutions?

Thank you very much

3

There are 3 answers

0
Jesse Sealand On BEST ANSWER

Numpy has this functionality built in with the method hstack

a = np.array([[[1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]],
       [[17, 18, 19, 20], 
        [21, 22, 23, 24], 
        [25, 26, 27, 28], 
        [29, 30, 31, 32]]])

np.hstack(a)

# array([[ 1,  2,  3,  4, 17, 18, 19, 20],
#        [ 5,  6,  7,  8, 21, 22, 23, 24],
#        [ 9, 10, 11, 12, 25, 26, 27, 28],
#        [13, 14, 15, 16, 29, 30, 31, 32]])
0
mozway On

You can use moveaxis to push the first axis in the end, then reshape in Fortran order:

np.moveaxis(a, 0, -1).reshape((a.shape[1], -1), order='F')

Output:

array([[ 1,  2,  3,  4, 17, 18, 19, 20],
       [ 5,  6,  7,  8, 21, 22, 23, 24],
       [ 9, 10, 11, 12, 25, 26, 27, 28],
       [13, 14, 15, 16, 29, 30, 31, 32]])
3
Guy On

You can use np.c_

np.c_[a[0], a[1]]

# [[ 1  2  3  4 17 18 19 20]
#  [ 5  6  7  8 21 22 23 24]
#  [ 9 10 11 12 25 26 27 28]
#  [13 14 15 16 29 30 31 32]]