2

I have 4 arrays and I want to concatenate them into one single array with interleaving. How do I do this?

>>> import numpy as np
>>> a = np.tile(0,(5,2))
>>> b = np.tile(1,(5,2))
>>> c = np.tile(2,(5,2))
>>> d = np.tile(3,(5,2))
>>> e = np.concatenate((a,b,c,d),axis=1)
>>> e
    array([[0, 0, 1, 1, 2, 2, 3, 3],
           [0, 0, 1, 1, 2, 2, 3, 3],
           [0, 0, 1, 1, 2, 2, 3, 3],
           [0, 0, 1, 1, 2, 2, 3, 3],
           [0, 0, 1, 1, 2, 2, 3, 3]])

This gives just the concatenation.

However, my desired_output is:

>>> desired_output
    array([[0, 1, 2, 3, 0, 1, 2, 3],
           [0, 1, 2, 3, 0, 1, 2, 3],
           [0, 1, 2, 3, 0, 1, 2, 3],
           [0, 1, 2, 3, 0, 1, 2, 3],
           [0, 1, 2, 3, 0, 1, 2, 3]])

I mean I know I can select the interleaved columns from e using:

>>> f = e[:, ::2]
>>> array([[0, 1, 2, 3],
           [0, 1, 2, 3],
           [0, 1, 2, 3],
           [0, 1, 2, 3],
           [0, 1, 2, 3]])

But how do I make one big array?

bFig8
  • 417
  • 2
  • 7
  • 20

1 Answers1

5

Use np.dstack or np.stack to stack along the last axis that gives us a 3D array and then reshape back to 2D -

np.dstack([a,b,c,d]).reshape(a.shape[0],-1)
np.stack([a,b,c,d],axis=2).reshape(a.shape[0],-1)
Divakar
  • 218,885
  • 19
  • 262
  • 358