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

PythonArraysNumpy

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimYView Question on Stackoverflow
Solution 1 - PythonJon ClementsView Answer on Stackoverflow
Solution 2 - PythonzenpoyView Answer on Stackoverflow