What is the equivalent of "zip()" in Python's numpy?

I am trying to do the following but with numpy arrays:

x = [(0.1, 1.), (0.1, 2.), (0.1, 3.), (0.1, 4.), (0.1, 5.)]
normal_result = zip(*x)

This should give a result of:

normal_result = [(0.1, 0.1, 0.1, 0.1, 0.1), (1., 2., 3., 4., 5.)]

But if the input vector is a numpy array:

y = np.array(x)
numpy_result = zip(*y)
print type(numpy_result)

It (expectedly) returns a:

<type 'list'>

The issue is that I will need to transform the result back into a numpy array after this.

What I would like to know is what is if there is an efficient numpy function that will avoid these back-and-forth transformations?


You can just transpose it...

>>> a = np.array([(0.1, 1.), (0.1, 2.), (0.1, 3.), (0.1, 4.), (0.1, 5.)])
>>> a
array([[ 0.1,  1. ],
       [ 0.1,  2. ],
       [ 0.1,  3. ],
       [ 0.1,  4. ],
       [ 0.1,  5. ]])
>>> a.T
array([[ 0.1,  0.1,  0.1,  0.1,  0.1],
       [ 1. ,  2. ,  3. ,  4. ,  5. ]])

Try using dstack:

>>> from numpy import *
>>> a = array([[1,2],[3,4]]) # shapes of a and b can only differ in the 3rd dimension (if present)
>>> b = array([[5,6],[7,8]])
>>> dstack((a,b)) # stack arrays along a third axis (depth wise)
array([[[1, 5],
        [2, 6]],
       [[3, 7],
        [4, 8]]])

so in your case it would be:

x = [(0.1, 1.), (0.1, 2.), (0.1, 3.), (0.1, 4.), (0.1, 5.)]
y = np.array(x)
np.dstack(y)

>>> array([[[ 0.1,  0.1,  0.1,  0.1,  0.1],
    [ 1. ,  2. ,  3. ,  4. ,  5. ]]])