python - Numpy:如何迭代地将 3D 数组堆叠成行?
问题描述
我正在尝试将导致 3D 数组的计算结果堆叠成行(轴 = 0)。我不提前知道结果。
import numpy as np
h = 10
w = 20
c = 30
result_4d = np.??? # empty
for i in range(5):
result_3d = np.zeros((h, w, c)) #fake calculation
result_4d = np.??? # stacked result_3ds on axis=0
return result_4d
我已经尝试了 numpy *stack 调用的各种排列,但我不可避免地遇到了形状不匹配错误。
解决方案
先把它放在一个列表中,然后再堆叠。
h = 10
w = 20
c = 30
l = []
for i in range(5):
result_3d = np.zeros((h, w, c)) #fake calculation
l.append(result_3d)
res = np.stack(l, axis=-1)
res.shape # (10, 20, 30, 5)
# move stacked axis around ...
np.transpose(res, (3,0,1,2)).shape # (5, 10, 20, 30)
如果你想循环更新,你可以这样做:
res = ''
for i in range(5):
result_3d = np.zeros((h, w, c)) #fake calculation
if type(res) is str:
res = np.array([result_3d]) # add dimension
continue
res = np.vstack((res, np.array([result_3d]))) # stack on that dimension
res.shape # (5, 10, 20, 30)
推荐阅读
- view - 向现有视图添加自定义字段的问题
- javascript - 如何使用 Javascript 更改默认日期选择器日历的设计
- haskell - 为什么 (pure [] 3) 的类型是“[a]”?
- c# - 锚点定位后应用程序突然关闭
- html - 如何将pdf页面渲染成svg
- sql - SQL Server 迭代数百万行的更好方法
- entity-framework - EF6:尽管 IsRequired,迁移仍会生成可为空的字符串
- python - Django:添加一个拥有自己的模型集的测试
- javascript - 可滚动的图片库循环在最后一张图片之后工作,它应该再次从第一张图片开始
- postgresql - 这种自联接可以进一步优化吗?