首页 > 解决方案 > 将矩阵附加到 numpy 数组

问题描述

testMat1 = np.array([[1,2,3,4],[4,5,6,7]])
testMat2 = np.array([[7,8,9,10],[10,11,12,13]])
testMat3 = np.array([[2,4,6,8],[3,5,7,9]])

这是三个形状矩阵(2, 4)

如何将它们组合成一个带有 shape 的多维数组(3, 2, 4)

np.array([testMat1, testMat2, testMat3])工作正常,但这不是我想要的,因为我将不断向数组添加更多矩阵。我需要一种将新矩阵附加到数组的方法。我尝试使用np.append,但似乎不是为了这个目的。

标签: pythonarraysnumpymultidimensional-arrayappend

解决方案


您可以使用np.vstack()垂直堆叠阵列。

在你的情况下,命令看起来像这样: combined = np.vstack(([testMat1], [testMat2], [testMat3])) 这会给你形状 (3, 2, 4)

您可以不断添加更多数组并使用以下方法更新它: combined = np.vstack((combined, [testMat4])) 这将为您提供形状 (4, 2, 4)


推荐阅读