2013-07-31 4 views
23

Zum Beispiel Ich habe 2 Arraysin Numpy, wie zwei 2-D-Arrays zip?

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

Wie kann ich zipa und b so erhalte ich

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

?

Antwort

26

können Sie dstack verwenden:

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

Für Python 3+ Sie das zip Objekt Iterator erweitern müssen:

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

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

Wenn Sie Tupel haben müssen. Bitte beachten Sie, dass dies schrecklich ineffizient:

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

Dank! 'dstack' funktioniert super für mich! – LWZ

+0

Für den zweiten Befehl bekomme ich 'TypeError: ein Byte-ähnliches Objekt ist erforderlich, nicht 'zip' - warum ist das? – Make42

+0

@ Make42 In Python 3 gibt 'zip' einen Iterator zurück. Siehe bearbeitete Antwort. – Daniel

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