用交错列连接两个矩阵

时间:2017-11-10 02:57:37

标签: python numpy matrix

我有两个2-D数组,我想将它们连接在一起交错列

初始数组(每个都有形状(3,8)):

array([[ 107,  115,  132,  138,  128,  117,  121,135],
       [ 149,  152,  151,  143,  146,  149,  149,148], 
       [ 152,  142,  146 , 141,  143,  148,  149, 153]])

array([[ 25,  28,  28,  25,  23,  21,  20,  18],
       [  3,   3,   2,   2,  10,  12,  12,  1],
       [  1,   0,   2,   0,   0,   0,   0,   1]])

结果(形状为6x8):

    array([[ 107,  115,  132,  138,  128,  117,  121, 135],
           [  25,   28,   28,   25,   23,   21,   20,  18],
           [ 149,  152,  151,  143,  146,  149,  149, 148], 
           [   3,    3,    2,    2,   10,   12,   12,  13],
           [ 152,  142,  146 , 141,  143,  148,  149, 153]
           [   1,    0,    2,    0,    0,    0,    0,   1]])

我知道应该可以通过一系列重塑进行,但我无法弄清楚如何!

1 个答案:

答案 0 :(得分:2)

您可以对两个数组进行列堆叠,然后重新整形:

np.column_stack((a, b)).reshape(-1, a.shape[1])

#array([[107, 115, 132, 138, 128, 117, 121, 135],
#       [ 25,  28,  28,  25,  23,  21,  20,  18],
#       [149, 152, 151, 143, 146, 149, 149, 148],
#       [  3,   3,   2,   2,  10,  12,  12,   1],
#       [152, 142, 146, 141, 143, 148, 149, 153],
#       [  1,   0,   2,   0,   0,   0,   0,   1]])

或类似地:

np.concatenate((a, b), axis=1).reshape(-1, a.shape[1])