Search code examples
pythonarraysnumpyzip

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

?


Solution

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