Python的numpy中“zip()”的等效函数是什么?

66

我正在尝试使用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函数可以避免来回转换?
2个回答

85

你可以只是将它转置...

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

1
聪明 - 很好用的数学 - WestCoastProjects

36

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

2
将一个二维数组添加一个额外的维度。如果你想要类似于 OP 所需的东西,你需要取 dstacked 数组的第一个元素。 - benjwadams
1
Numpy中的np.stack是矩阵最接近于zip的函数。 arrays = (x, y); np.stack(arrays, axis=len(arrays)) - CMCDragonkai
4
还有一个np.column_stack函数,这可能是楼主所需要的。 - RecencyEffect
不是完全正确的答案,但了解这些对于你有用。 - WestCoastProjects

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接