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

前端 未结 2 633
灰色年华
灰色年华 2020-12-25 09:39

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)

相关标签:
2条回答
  • 2020-12-25 09:53

    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. ]])
    
    0 讨论(0)
  • 2020-12-25 10:19

    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. ]]])
    
    0 讨论(0)
提交回复
热议问题