Python 的 numpy 中“zip()”的等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12744778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:46:09  来源:igfitidea点击:

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

pythonarraysnumpy

提问by TimY

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

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

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:

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

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.

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

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

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

采纳答案by Jon Clements

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

回答by zenpoy

Try using dstack:

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