在新维度上使用np.stack在循环中堆叠ndarrays(创建ndarrays数组)



由于以下问题,我无法在新维度上堆叠numpy数组:

>>> a = np.zeros(shape=(100,100))
>>> b = np.zeros(shape=(100,100))
>>> c = np.stack((a, b))
>>> c.shape
(2, 100, 100)
>>> d = np.zeros(shape=(100,100))
>>> c = np.stack((c, d))
Traceback (most recent call last):
File "/lib/python3.7/site-packages/numpy/core/shape_base.py", line 426, in stack
raise ValueError('all input arrays must have the same shape')
ValueError: all input arrays must have the same shape

我打算在循环中使用它的方式是:

final = None
for next_mat in mats:
final = next_mat if final is None else np.stack((final, next_mat))

我该如何实现它?非常感谢。

我宁愿存储所有数组并堆叠一次:

cum_arr = []
for next_mat in mats:
cum_arr.append(next_mat)
np.stack(cum_arr)

或者,如果您有mats列表:

np.stack(mats)

由于stack要求所有输入都是相同的形状,如果您想在每个循环中进行堆栈,可以使用vstack。还需要将尺寸标注从(100100(扩展到(1100100(。

final = None
for next_mat in mats:
next_mat = np.expand_dims(next_mat, 0)
final = next_mat if final is None else np.vstack((final, next_mat))

最新更新