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)]])
?
The numpy. column_stack() function is another method that can be used to zip two 1D arrays into a single 2D array in Python.
In Python to declare a new 2-dimensional array we can easily use the combination of arange and reshape() method. The reshape() method is used to shape a numpy array without updating its data and arange() function is used to create a new array.
The zip() function in Python programming is a built-in standard function that takes multiple iterables or containers as parameters. An iterable in Python is an object that you can iterate over or step through like a collection. You can use the zip() function to map the same indexes of more than one iterable.
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')])
np.array([zip(x,y) for x,y in zip(a,b)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With