This question already has an answer here:
这个问题在这里已有答案:
- How to merge 2 numpy arrays? 3 answers
如何合并2个numpy数组? 3个答案
I have two numpy matrix A and B. A is 1000 x 6, looks like:
我有两个numpy矩阵A和B. A是1000 x 6,看起来像:
[ [a1_1, a1_2, a1_3, a1_4, a1_5,a1_6],
[a2_1, a2_2, a2_3, a2_4, a2_5,a2_6],
[a3_1, a3_2, a3_3, a3_4, a3_5,a3_6],
:
:
[a1000_1, a1000_2, a1000_3, a1000_4, a1000_5,a1000_6]]
B is also 1000x6 and is like:
B也是1000x6,就像:
[ [b1_1, b1_2, b1_3, b1_4, b1_5,b1_6],
[b2_1, b2_2, b2_3, b2_4, b2_5,b2_6],
[b3_1, b3_2, b3_3, b3_4, b3_5,b3_6],
:
:
[b1000_1, b1000_2, b1000_3, b1000_4, b1000_5,b1000_6]]
then I want to create a 3D matrix: 1000x6x2, which should looks like:
然后我想创建一个3D矩阵:1000x6x2,它看起来像:
[[[a1_1, b1_1], [a1_2, b1_2], [a1_3, b1_3], [a1_4, b1_4], [a1_5, b1_5],[a1_6, b1_6]],
[[a2_1, b2_1], [a2_2, b2_2], [a2_3, b2_3], [a2_4, b2_4], [a2_5, b2_5],[a2_6, b2_6]],
[[a3_1, b3_1], [a3_2, b3_2], [a3_3, b3_3], [a3_4, b3_4], [a3_5, b3_5],[a3_6, b3_6]],
:
:
[[a1000_1, b1000_1], [a1000_2, b1000_2], [a1000_3, b1000_3], [a1000_4, b1000_4], [a1000_5, b1000_5],[a1000_6, b1000_6]]]
I can create an empty 1000x6x2 matrix C, then iterate matrix A and B to assign the value in C one by one. But I am wondering is there a more elegant way to combine A and B, reshape and get the matrix C? Thanks!
我可以创建一个空的1000x6x2矩阵C,然后迭代矩阵A和B,逐个分配C中的值。但我想知道是否有一种更优雅的方式来组合A和B,重塑并获得矩阵C?谢谢!
1 个解决方案
#1
1
You can use numpy.dstack
which Stack arrays in sequence depth wise (along third axis):
你可以使用numpy.dstack堆栈数组顺序深度(沿第三轴):
C = np.dstack((A, B))
Or numpy.stack((A,B),axis=-1)
:
import numpy as np
A = np.arange(6000).reshape(1000,6)
B = np.arange(6000).reshape(1000,6)
C = np.dstack((A, B))
C.shape
# (1000, 6, 2)
C = np.stack((A,B), axis=-1)
C.shape
# (1000, 6, 2)
#1
1
You can use numpy.dstack
which Stack arrays in sequence depth wise (along third axis):
你可以使用numpy.dstack堆栈数组顺序深度(沿第三轴):
C = np.dstack((A, B))
Or numpy.stack((A,B),axis=-1)
:
import numpy as np
A = np.arange(6000).reshape(1000,6)
B = np.arange(6000).reshape(1000,6)
C = np.dstack((A, B))
C.shape
# (1000, 6, 2)
C = np.stack((A,B), axis=-1)
C.shape
# (1000, 6, 2)