我有以下 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 得到这个结果?
我有以下 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
——
np.hstack((X,Y,Z))
或者np.stack
沿着axis=0
然后做多暗淡转置 -
np.stack((X,Y,Z),axis=0).T
重塑适用于数组,而不是将数组堆叠或连接在一起。所以,reshape
单独在这里没有意义。
有人可能会争论使用np.reshape
给我们想要的输出,就像这样 -
np.reshape((X,Y,Z),(3,4)).T
但是,它在幕后进行堆叠操作,AFAIK 可以将其转换为数组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]])