首页 > 解决方案 > 如何在 Python 中动态地将数组添加到 Numpy 堆栈中

问题描述

这是我的 numpy 数组

我必须动态添加它们

意味着,x 来自循环,我想像这样添加它们np.stack,我附上了下面的代码

x=np.array(([1,2],[1,2],[1,2],[1,2],[1,2]))
b=x
z=np.stack((x, b))
z
#output
 array([[[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]], 
      [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]])

如果将 b 再次附加到zusing 中 np.stack((x, b)),它会给我一个错误

ValueError: all input arrays must have the same shape

谁能告诉我该怎么做?

标签: pythonnumpy

解决方案


numpy中,堆叠数组的方式有很多种;您的初始数组的形状(5,2)如下:

[[1 2]
 [1 2]
 [1 2]
 [1 2]
 [1 2]]

您可以使用它水平堆叠np.hstack(x,b)以获得:

[[1 2 1 2]
 [1 2 1 2]
 [1 2 1 2]
 [1 2 1 2]
 [1 2 1 2]] # shape: (5, 4), i.e. five arrays of shape 4

或垂直堆叠使用np.vstack(x,b)以获得

[[1 2]
 [1 2]
 [1 2]
 [1 2]
 [1 2]
 [1 2]
 [1 2]
 [1 2]
 [1 2]
 [1 2]] # shape: (10, 2), i.e. 10 arrays of shape 2

或堆叠到深度使用np.dstack(x,b)以获得:

[[[1 1]
  [2 2]]

 [[1 1]
  [2 2]]

 [[1 1]
  [2 2]]

 [[1 1]
  [2 2]]

 [[1 1]
  [2 2]]] # shape: (5, 2, 2), i.e. five arrays of shape (2,2)

但是,当您使用np.stack()时,numpy 将创建一个新轴来加入数组,例如:

[[[1 2]
  [1 2]
  [1 2]
  [1 2]
  [1 2]]

 [[1 2]             the new axis!
  [1 2]             |  i.e. two arrays of shape (5,2)
  [1 2]             |
  [1 2]             v
  [1 2]]] # shape: (2, 5, 2)

现在,这是您问题的解决方案:您尝试在循环中“追加”数组,但np.stack()会尝试在每一步添加一个新维度,这将无法按预期工作。我想,根据您想要实现的形状,您应该使用其他方法之一。


推荐阅读