2013-07-31 16 views
23

Per esempio io ho 2 campiin Numpy, come chiudere due array 2D?

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

Come posso zipa e b così ottengo

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

?

risposta

26

È possibile utilizzare dstack:

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

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

Se è necessario disporre di tuple:

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

Per Python 3+ è necessario espandere l'oggetto zip iteratore. Si prega di notare che questo è terribilmente inefficiente:

>>> 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')]) 
+0

Grazie! 'dstack' funziona alla grande per me! – LWZ

+0

Per il secondo comando ottengo 'TypeError: è richiesto un oggetto simile a un byte, non 'zip'' - perché? – Make42

+0

@ Make42 In Python 3 'zip' restituisce un iteratore. Vedi la risposta modificata. – Daniel

5
np.array([zip(x,y) for x,y in zip(a,b)])