Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Numpy, how to zip two 2-D arrays?

For example I have 2 arrays

a = array([[0, 1, 2, 3],
           [4, 5, 6, 7]])
b = array([[0, 1, 2, 3],
           [4, 5, 6, 7]])

How can I zip a and b so I get

c = array([[(0,0), (1,1), (2,2), (3,3)],
           [(4,4), (5,5), (6,6), (7,7)]])

?

like image 323
LWZ Avatar asked Jul 31 '13 02:07

LWZ


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 you create a 2D NumPy array in Python?

In Python to declare a new 2-dimensional array we can easily use the combination of arange and reshape() method. The reshape() method is used to shape a numpy array without updating its data and arange() function is used to create a new array.

How do you zip a matrix in Python?

The zip() function in Python programming is a built-in standard function that takes multiple iterables or containers as parameters. An iterable in Python is an object that you can iterate over or step through like a collection. You can use the zip() function to map the same indexes of more than one iterable.


2 Answers

You can use dstack:

>>> np.dstack((a,b))
array([[[0, 0],
        [1, 1],
        [2, 2],
        [3, 3]],

       [[4, 4],
        [5, 5],
        [6, 6],
        [7, 7]]])

If you must have tuples:

>>> np.array(zip(a.ravel(),b.ravel()), dtype=('i4,i4')).reshape(a.shape)
array([[(0, 0), (1, 1), (2, 2), (3, 3)],
       [(4, 4), (5, 5), (6, 6), (7, 7)]],
      dtype=[('f0', '<i4'), ('f1', '<i4')])

For Python 3+ you need to expand the zip iterator object. Please note that this is horribly inefficient:

>>> np.array(list(zip(a.ravel(),b.ravel())), dtype=('i4,i4')).reshape(a.shape)
array([[(0, 0), (1, 1), (2, 2), (3, 3)],
       [(4, 4), (5, 5), (6, 6), (7, 7)]],
      dtype=[('f0', '<i4'), ('f1', '<i4')])
like image 95
Daniel Avatar answered Oct 07 '22 01:10

Daniel


np.array([zip(x,y) for x,y in zip(a,b)])
like image 25
Aert Avatar answered Oct 06 '22 23:10

Aert