How to zip two 1d numpy array to 2d numpy array [duplicate]

The answer lies in your question:

np.array(list(zip(a,b)))

Edit:

Although my post gives the answer as requested by the OP, the conversion to list and back to NumPy array takes some overhead (noticeable for large arrays).

Hence, dstack would be a computationally efficient alternative (ref. @zipa’s answer). I was unaware of dstack at the time of posting this answer so credits to @zipa for introducing it to this post.

Edit 2:

As can be seen in the duplicate question, np.c_ is even shorter than np.dstack.

>>> import numpy as np
>>> a = np.arange(1, 6)
>>> b = np.arange(6, 11)
>>> 
>>> a
array([1, 2, 3, 4, 5])
>>> b
array([ 6,  7,  8,  9, 10])
>>> np.c_[a, b]
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])

Leave a Comment