For example I have 2 arrays
JavaScript
x
5
1
a = array([[0, 1, 2, 3],
2
[4, 5, 6, 7]])
3
b = array([[0, 1, 2, 3],
4
[4, 5, 6, 7]])
5
How can I zip
a
and b
so I get
JavaScript
1
3
1
c = array([[(0,0), (1,1), (2,2), (3,3)],
2
[(4,4), (5,5), (6,6), (7,7)]])
3
?
Advertisement
Answer
You can use dstack:
JavaScript
1
11
11
1
>>> np.dstack((a,b))
2
array([[[0, 0],
3
[1, 1],
4
[2, 2],
5
[3, 3]],
6
7
[[4, 4],
8
[5, 5],
9
[6, 6],
10
[7, 7]]])
11
If you must have tuples:
JavaScript
1
5
1
>>> np.array(zip(a.ravel(),b.ravel()), dtype=('i4,i4')).reshape(a.shape)
2
array([[(0, 0), (1, 1), (2, 2), (3, 3)],
3
[(4, 4), (5, 5), (6, 6), (7, 7)]],
4
dtype=[('f0', '<i4'), ('f1', '<i4')])
5
For Python 3+ you need to expand the zip
iterator object. Please note that this is horribly inefficient:
JavaScript
1
5
1
>>> np.array(list(zip(a.ravel(),b.ravel())), dtype=('i4,i4')).reshape(a.shape)
2
array([[(0, 0), (1, 1), (2, 2), (3, 3)],
3
[(4, 4), (5, 5), (6, 6), (7, 7)]],
4
dtype=[('f0', '<i4'), ('f1', '<i4')])
5