假设我有两个二维矩阵A和B,我想将A中的每一列与B中相应的列连接起来。例如:
A = array([[1, 1],
[1, 1]])
B = array([[2, 3],
[2, 3]])
所以我期望的结果是:
array([[1, 2, 1, 3],
[1, 2, 1, 3]])
x = np.concatenate((A, B)).reshape(2,2,2)
x
# array([[[1, 1],
# [1, 1]],
# [[2, 3],
# [2, 3]]])
x.transpose(1,2,0).reshape(2,4)
# array([[1, 2, 1, 3],
# [1, 2, 1, 3]])
最简单的方式是通过列优先(Fortran)排序实现:
import numpy as np
def mix_arrays(a,b):
return np.concatenate((a,b)).reshape(2,4, order='F')
通过您提供的输入,A
和B
:
>>> mix_arrays(A,B)
array([[1, 2, 1, 3],
[1, 2, 1, 3]])
def mix_matrices(a,b):
(ma,na) = a.shape
(mb,nb) = b.shape
if mb < ma:
ma = mb
c = np.zeros((ma,na+nb))
c[:ma,::2] = a[:ma]
c[:ma,1::2] = b[:ma]
return c
This generates:
>>> mix_matrices(A,B)
array([[ 1., 2., 1., 3.],
[ 1., 2., 1., 3.]])
这里是涉及np.dstack
和 reshape
的示例 -
np.dstack((A,B)).reshape(-1,A.shape[1]*2)
示例运行 -
In [44]: A
Out[44]:
array([[2, 7, 3, 0, 8],
[1, 0, 6, 7, 6],
[3, 4, 7, 7, 6],
[0, 3, 7, 5, 4]])
In [45]: B
Out[45]:
array([[8, 4, 3, 8, 0],
[3, 1, 8, 8, 2],
[8, 5, 8, 8, 4],
[1, 0, 6, 1, 7]])
In [46]: np.dstack((A,B)).reshape(-1,A.shape[1]*2)
Out[46]:
array([[2, 8, 7, 4, 3, 3, 0, 8, 8, 0],
[1, 3, 0, 1, 6, 8, 7, 8, 6, 2],
[3, 8, 4, 5, 7, 8, 7, 8, 6, 4],
[0, 1, 3, 0, 7, 6, 5, 1, 4, 7]])
a
有三行)? - Willem Van Onsem