首页 > 解决方案 > 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 调用的各种排列,但我不可避免地遇到了形状不匹配错误。

标签: pythonnumpy

解决方案


先把它放在一个列表中,然后再堆叠。

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)

推荐阅读