Tim*_*imY 58 python arrays numpy
我试图执行以下操作,但使用numpy数组:
x = [(0.1, 1.), (0.1, 2.), (0.1, 3.), (0.1, 4.), (0.1, 5.)]
normal_result = zip(*x)
Run Code Online (Sandbox Code Playgroud)
这应该给出一个结果:
normal_result = [(0.1, 0.1, 0.1, 0.1, 0.1), (1., 2., 3., 4., 5.)]
Run Code Online (Sandbox Code Playgroud)
但是如果输入向量是一个numpy数组:
y = np.array(x)
numpy_result = zip(*y)
print type(numpy_result)
Run Code Online (Sandbox Code Playgroud)
它(预期)返回:
<type 'list'>
Run Code Online (Sandbox Code Playgroud)
问题是我需要在此之后将结果转换回numpy数组.
我想知道的是,如果有一个有效的numpy函数可以避免这些来回转换?
Jon*_*nts 76
你可以转置它......
>>> 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. ]])
Run Code Online (Sandbox Code Playgroud)
zen*_*poy 35
尝试使用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]]])
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下它将是:
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. ]]])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
60032 次 |
最近记录: |