简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM