【问题标题】:How to append multiple matrices in python如何在python中附加多个矩阵
【发布时间】:2021-04-01 11:35:09
【问题描述】:

我已阅读以下相关讨论 What's the simplest way to extend a numpy array in 2 dimensions?

但是,如果我想扩展多个矩阵,例如

A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
F = np.append(A,[[B]],0)

然而,蟒蛇说

ValueError: 所有输入数组的维数必须相同,但索引 0 处的数组有 2 维,索引 1 处的数组有 4 维

我想将 B 放在矩阵 A 的“下方”,并将 C 放在矩阵 B 的“下方”。
所以,F 应该是一个 6X2 矩阵。

如何做到这一点?谢谢!

【问题讨论】:

  • 因为你所有的数组都有相同的形状,你可以简单地np.concatenate([A,B,C], axis=0)。我反对在您的链接答案中使用np.append,并将再次这样做。
  • np.array([[B]])的形状是什么?

标签: python numpy matrix append


【解决方案1】:

我相信 np.concatenate 应该可以解决问题

    A = np.matrix([[1,2],[3,4]])
    B = np.matrix([[3,4],[5,6]])
    C = np.matrix([[7,8],[5,6]])
    ABC = np.concatenate([A,B,C],axis = 0) # axis 0 stacks it one above the other
    
    print("Shape : ",ABC.shape)
    print(ABC)

输出:

    Shape : (6, 2)
    matrix(
    [[1, 2],
    [3, 4],
    [3, 4],
    [5, 6],
    [7, 8],
    [5, 6]])

【讨论】:

  • 但是为什么两个concatenate?使用[A,B,C] 做一件事效率更高。
【解决方案2】:

尝试使用 numpy.concatenate (https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html):

A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
# F = np.append(A,[[B]],0)
F = np.concatenate((A, B, C), axis=1)

将轴参数更改为 0 以“垂直”组合矩阵:

print(np.concatenate((A, B, C), axis=1))

[[1 2 3 4 7 8]
[3 4 5 6 5 6]]

print(np.concatenate((A, B, C), axis=0))

[[1 2]
[3 4]
[3 4]
[5 6]
[7 8]
[5 6]]

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 2016-10-02
    • 2017-12-07
    • 2021-12-11
    • 2017-09-06
    • 2013-11-18
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多