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

Question:

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)]])

?

Asked By: LWZ

||

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')])
Answered By: Daniel
np.array([zip(x,y) for x,y in zip(a,b)])
Answered By: Aert

You could also specify the transpose indices:

c = np.array([a,b]).transpose(1,2,0)
Answered By: Andrew
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.