gpt4 book ai didi

python - Numpy:如何迭代地将 3D 数组堆叠在行中?

转载 作者:行者123 更新时间:2023-12-01 08:49:33 25 4
gpt4 key购买 nike

我正在尝试将产生 3D 数组的计算结果堆叠成行(axis=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)

关于python - Numpy:如何迭代地将 3D 数组堆叠在行中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53181969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com