python - 如何在 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 再次附加到z
using 中 np.stack((x, b))
,它会给我一个错误
ValueError: all input arrays must have the same shape
谁能告诉我该怎么做?
解决方案
在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()
会尝试在每一步添加一个新维度,这将无法按预期工作。我想,根据您想要实现的形状,您应该使用其他方法之一。
推荐阅读
- pandas - 具有多个布尔条件的 panda loc 创建子集
- heroku - Heroku 自定义域不起作用 - Django 部署
- python - plotly 3D Topographical 3D Surface Plot with pandas dataframe
- dynamic-programming - 动态规划中回溯解决方案的制表与记忆(前 LCS)
- c# - 无法在 sharepoint C# 代码中上传文件
- scheme - 在元循环评估器中添加基元
- javascript - 制表符和 dat.GUI 在一起
- r - 无法为 rga.open R 脚本创建 Docker 映像
- api - 找不到可以按受欢迎程度排序并按类型搜索的书籍 Api
- html - 引导卡片 - 卡片中的文字