Interlace Rows 2D Numpy Array

Viewed 191

I have a 2D numpy array that looks like this

array([[x1,x2,x3,x4],
       [x2,x3,x4,x5],
       [x3,x4,x5,x6],
       [y1,y2,y3,y4],
       [y2,y3,y4,y5],
       [y3,y4,y5,y6],])

I want to interlace the rows such that the array to look like this

array([[x1,x2,x3,x4],
       [y1,y2,y3,y4],
       [x2,x3,x4,x5],
       [y2,y3,y4,y5],
       [x3,x4,x5,x6],
       [y3,y4,y5,y6],])
2 Answers
x = np.random.randint(10,size = (3,5))

Out[23]: 
array([[1, 5, 8, 4, 6],
       [8, 1, 7, 0, 8],
       [4, 7, 5, 2, 9]])

y = np.random.randint(10,size = (3,5))

Out[24]: 
array([[7, 4, 0, 5, 7],
       [4, 2, 8, 6, 1],
       [1, 2, 8, 6, 0]])

np.hstack((x,y)).reshape(6,5)

Out[25]: 
array([[1, 5, 8, 4, 6],
       [7, 4, 0, 5, 7],
       [8, 1, 7, 0, 8],
       [4, 2, 8, 6, 1],
       [4, 7, 5, 2, 9],
       [1, 2, 8, 6, 0]])

Two related methods:

# create example array
A = np.sum(np.ix_(np.array(list("abcxyz"),"O"),np.array(list("1234"),"O"))).astype("U2")
A
# array([['a1', 'a2', 'a3', 'a4'],
#        ['b1', 'b2', 'b3', 'b4'],
#        ['c1', 'c2', 'c3', 'c4'],
#        ['x1', 'x2', 'x3', 'x4'],
#        ['y1', 'y2', 'y3', 'y4'],
#        ['z1', 'z2', 'z3', 'z4']], dtype='<U2')

You can use reshaping and swapaxes:

A.reshape(2,-1,A.shape[-1]).swapaxes(0,1).reshape(A.shape)

or you can reshape twice, using FORTRAN order in one but not the other direction:

A.reshape(-1,2,A.shape[-1],order='F').reshape(A.shape)

or

A.reshape(2,-1,A.shape[-1]).reshape(A.shape,order="F")

Result in all cases

# array([['a1', 'a2', 'a3', 'a4'],
#        ['x1', 'x2', 'x3', 'x4'],
#        ['b1', 'b2', 'b3', 'b4'],
#        ['y1', 'y2', 'y3', 'y4'],
#        ['c1', 'c2', 'c3', 'c4'],
#        ['z1', 'z2', 'z3', 'z4']], dtype='<U2')
Related