1

I have two 2-D arrays and I would like to concatenate them interleaving the columns

Initial arrays (with shape (3, 8) each):

array([[ 107,  115,  132,  138,  128,  117,  121,135],
       [ 149,  152,  151,  143,  146,  149,  149,148], 
       [ 152,  142,  146 , 141,  143,  148,  149, 153]])

array([[ 25,  28,  28,  25,  23,  21,  20,  18],
       [  3,   3,   2,   2,  10,  12,  12,  1],
       [  1,   0,   2,   0,   0,   0,   0,   1]])

Result (with shape 6x8):

    array([[ 107,  115,  132,  138,  128,  117,  121, 135],
           [  25,   28,   28,   25,   23,   21,   20,  18],
           [ 149,  152,  151,  143,  146,  149,  149, 148], 
           [   3,    3,    2,    2,   10,   12,   12,  13],
           [ 152,  142,  146 , 141,  143,  148,  149, 153]
           [   1,    0,    2,    0,    0,    0,    0,   1]])

I know it should be possible to do it with a series of reshapes, but I couldn't figure out how!

Sojers
  • 87
  • 2
  • 8

1 Answers1

3

You can column stack the two arrays, then reshape:

np.column_stack((a, b)).reshape(-1, a.shape[1])

#array([[107, 115, 132, 138, 128, 117, 121, 135],
#       [ 25,  28,  28,  25,  23,  21,  20,  18],
#       [149, 152, 151, 143, 146, 149, 149, 148],
#       [  3,   3,   2,   2,  10,  12,  12,   1],
#       [152, 142, 146, 141, 143, 148, 149, 153],
#       [  1,   0,   2,   0,   0,   0,   0,   1]])

Or similarly:

np.concatenate((a, b), axis=1).reshape(-1, a.shape[1])
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Thanks! I knew I had to concatenate and reshape but I didn't know which indexes to use. Could you explain the use of the -1? – Sojers Nov 10 '17 at 10:00
  • As from [docs](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.reshape.html), *One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.* so in this case, it's the same as `.reshape(a.shape[0]*2, a.shape[1])`. – Psidom Nov 10 '17 at 14:29
  • Also see this answer for the meaning of -1 in `reshape` https://stackoverflow.com/a/41777769/12814841 – Craig Nathan Jul 02 '21 at 13:58