【问题标题】:What is the equivalent of "zip()" in Python's numpy?Python numpy 中的“zip()”等价物是什么?
【发布时间】:2012-09-26 12:32:56
【问题描述】:

我正在尝试使用 numpy 数组执行以下操作:

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

这应该给出以下结果:

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

但是如果输入向量是一个numpy数组:

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

它(预期)返回一个:

<type 'list'>

问题是我需要在此之后将结果转换回 numpy 数组。

我想知道的是,是否有一个有效的 numpy 函数可以避免这些来回转换?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    尝试使用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]]])
    

    所以你的情况是:

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

    【讨论】:

    • 向二维数组添加一个额外的维度。如果您想要类似于 OP 想要的东西,则必须获取 dstacked 数组的第一个元素。
    • Numpy np.stack 是最接近 zip 的矩阵。 arrays = (x, y); np.stack(arrays, axis=len(arrays)).
    • 还有n​​p.column_stack,可能是OP需要的。
    • 不完全是正确的答案,但了解一下很有用
    【解决方案2】:

    你可以转置它...

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

    【讨论】:

    • 聪明——数学很好用
    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 2018-08-26
    • 2013-10-18
    • 1970-01-01
    • 2011-09-03
    • 2011-03-07
    相关资源
    最近更新 更多