Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy concatenate arrays with interleaving

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?

like image 980
bFig8 Avatar asked Feb 27 '26 08:02

bFig8


1 Answers

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)
like image 136
Divakar Avatar answered Mar 02 '26 14:03

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!