Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

I have two numpy 1d arrays, e.g:

a = np.array([1,2,3,4,5]) b = np.array([6,7,8,9,10]) 

Then how can I get one 2d array [[1,6], [2,7], [3,8], [4,9], [5, 10]]?

like image 948
zjffdu Avatar asked Jun 07 '17 09:06

zjffdu


People also ask

Can I zip two NumPy arrays?

The numpy. column_stack() function is another method that can be used to zip two 1D arrays into a single 2D array in Python.

How do I copy a NumPy array to another NumPy array?

Conclusion: to copy data from a numpy array to another use one of the built-in numpy functions numpy. array(src) or numpy. copyto(dst, src) wherever possible.


2 Answers

If you have numpy arrays you can use dstack():

import numpy as np  a = np.array([1,2,3,4,5]) b = np.array([6,7,8,9,10])  c = np.dstack((a,b)) #or d = np.column_stack((a,b))  >>> c array([[[ 1,  6],         [ 2,  7],         [ 3,  8],         [ 4,  9],         [ 5, 10]]]) >>> d array([[ 1,  6],        [ 2,  7],        [ 3,  8],        [ 4,  9],        [ 5, 10]])  >>> c.shape (1, 5, 2) >>> d.shape (5, 2) 
like image 122
zipa Avatar answered Sep 17 '22 14:09

zipa


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]]) 
like image 44
Ébe Isaac Avatar answered Sep 18 '22 14:09

Ébe Isaac