我有以下numpy数组:
X = [[1],
[2],
[3],
[4]]
Y = [[5],
[6],
[7],
[8]]
Z = [[9],
[10],
[11],
[12]]
我想得到以下输出:
H = [[1,5,9],
[2,6,10],
[3,7,11]
[4,8,12]]
有没有办法使用numpy.reshape得到这个结果?
答案 0 :(得分:3)
您可以使用np.column_stack
-
np.column_stack((X,Y,Z))
或axis=1
上的np.concatenate
-
np.concatenate((X,Y,Z),axis=1)
或np.hstack
-
np.hstack((X,Y,Z))
或axis=0
沿着np.stack((X,Y,Z),axis=0).T
,然后进行多重调换 -
reshape
重塑应用于数组,而不是堆叠或连接数组。所以,np.reshape
在这里没有任何意义。
有人可能会争辩使用np.reshape((X,Y,Z),(3,4)).T
为我们提供所需的输出,就像这样 -
np.asarray
但是,在它做堆叠操作的引擎盖下,AFAIK可以用In [453]: np.asarray((X,Y,Z))
Out[453]:
array([[[ 1],
[ 2],
[ 3],
[ 4]],
[[ 5],
[ 6],
[ 7],
[ 8]],
[[ 9],
[10],
[11],
[12]]])
转换为数组 -
multi-dim transpose
我们只需要在其上使用3D
,为我们提供预期输出的In [454]: np.asarray((X,Y,Z)).T
Out[454]:
array([[[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]]])
数组版本 -
{{1}}
答案 1 :(得分:1)
这个(更快)的解决方案怎么样?
In [16]: np.array([x.squeeze(), y.squeeze(), z.squeeze()]).T
Out[16]:
array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])
效率(降序)
# proposed (faster) solution
In [17]: %timeit np.array([x.squeeze(), y.squeeze(), z.squeeze()]).T
The slowest run took 7.40 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.36 µs per loop
# Other solutions
In [18]: %timeit np.column_stack((x, y, z))
The slowest run took 5.18 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 9.18 µs per loop
In [19]: %timeit np.hstack((x, y, z))
The slowest run took 4.49 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 16 µs per loop
In [20]: %timeit np.reshape((x,y,z),(3,4)).T
10000 loops, best of 3: 21.6 µs per loop
In [20]: %timeit np.c_[x, y, z]
10000 loops, best of 3: 55.9 µs per loop
答案 2 :(得分:0)
不要忘记np.c_
(我不认为需要np.reshape
):
np.c_[X,Y,Z]
# array([[ 1, 5, 9],
# [ 2, 6, 10],
# [ 3, 7, 11],
# [ 4, 8, 12]])