[英]Reshape multiple numpy array
我有以下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获得此结果?
您可以使用np.column_stack
np.column_stack((X,Y,Z))
或者np.concatenate
沿axis=1
np.concatenate((X,Y,Z),axis=1)
np.hstack((X,Y,Z))
或沿axis=0
np.stack
然后进行多np.stack
转置-
np.stack((X,Y,Z),axis=0).T
整形应用于数组,而不是将数组堆叠或连接在一起。 因此,仅reshape
在这里没有意义。
有人可能会争辩说使用np.reshape
为我们提供所需的输出,就像这样-
np.reshape((X,Y,Z),(3,4)).T
但是,在np.asarray
进行了堆叠操作,而AFAIK可以通过np.asarray
转换为np.asarray
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]]])
这个(更快的)解决方案怎么样?
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
并且不要忘记np.c_
(我看不到需要np.reshape
):
np.c_[X,Y,Z]
# array([[ 1, 5, 9],
# [ 2, 6, 10],
# [ 3, 7, 11],
# [ 4, 8, 12]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.