Python 使用填充堆叠numpy数组

Python 使用填充堆叠numpy数组,python,arrays,numpy,Python,Arrays,Numpy,我有一个32个numpy数组的列表,每个数组都有shape(n,108,108,2),其中n在每个数组中是不同的。我想将所有这些元素堆叠起来,创建一个形状为(32,m,108,108,2)的numpy数组,其中m是ns中的最大值,较短的数组用零填充 我该怎么做 我昨天问过,但在我的例子中使用深度数组时,答案似乎不正确 具体地说,我最终采用了这个解决方案,它产生了最干净的代码: data = np.column_stack(zip_longest(*data, fillvalue=0)) 但现在

我有一个32个numpy数组的列表,每个数组都有shape
(n,108,108,2)
,其中
n
在每个数组中是不同的。我想将所有这些元素堆叠起来,创建一个形状为
(32,m,108,108,2)
的numpy数组,其中
m
n
s中的最大值,较短的数组用零填充

我该怎么做

我昨天问过,但在我的例子中使用深度数组时,答案似乎不正确

具体地说,我最终采用了这个解决方案,它产生了最干净的代码:

data = np.column_stack(zip_longest(*data, fillvalue=0))
但现在它抛出了这个错误:

ValueError: setting an array element with a sequence.
试试这个:

# Create matrices with random first axis length.
depth = np.random.randint(3,20,size=32)
l = []
lmax = 0
for i in depth:
    l.append(np.ones((i,10,10,2)))
    lmax = i if i > lmax else lmax

# Join the matrices:
new_l = []
for m in l:
    new_l.append(np.vstack([m, np.zeros((lmax-m.shape[0], 10, 10, 2))]))
master = np.stack(new_l, axis=0)
master.shape
>>> (32, 19, 10, 10, 2)

我发现在高维矩阵上使用
np.pad
几乎是不可能的-幸运的是,你所问的很简单,其中只有一个维度需要扩展,因此很容易使用
np.vstack
来堆叠一个零数组,使其符合一个新的形状。

我在这方面找到了一个神圣的答案

pad_sequences
功能正是我所需要的

from tensorflow.python.keras.preprocessing.sequence import pad_sequences
result = pad_sequences(imgs, padding='post')

在我的例子中,我需要堆叠不同宽度的图像,并在左侧填充零。 对我来说,这很有效:

np.random.seed(42)
image_batch = []
for i in np.random.randint(50,500,size=10):
image_batch.append(np.random.randn(32,i))
for im in image_batch:
    print(im.shape)
产出:(32152) (32, 485) (32, 398) (32, 320) (32, 156) (32, 121) (32, 238) (32, 70) (32, 152) (32171)

输出:(32485) (32, 485) (32, 485) (32, 485) (32, 485) (32, 485) (32, 485) (32, 485) (32, 485) (32485)

A=np.one((4,3))
border\u top\u bottom=np.零((A.形状[1])。重塑(1,A.形状[1]))
打印(np.vstack([border\u top\u bottom,A,border\u top\u bottom]))
温度=np.vstack([边框顶部底部,A,边框顶部底部])
边框右左=np.零((临时形状[0])。重塑(临时形状[0],1)
打印(np.hstack([np.hstack([border\u right\u left,temp,border\u right\u left]))

您昨天得到了一些好的答案,以及如何表达和测试想法的好例子。请遵循这些示例,并向我们展示您如何尝试解决新问题。我敢用这个标记吗?一个简单的想法-你可以将你的数组重新调整为2d,(n,108*108*2),然后应用其中一个2d解决方案。你说的中断是什么意思?异常被抛出,而不是想要的输出?@hpaulj我已经添加了建议的更多细节
zip\u longest
将起作用,但需要正确的
fillvalue。不是整数,而是形状正确的数组(例如np.零((108108,2))
def stack_images_rows_with_pad(list_of_images):
    func = lambda x: np.array(list(zip_longest(*x, fillvalue=0))) # applied row wise
    return np.array(list(map(func, zip(*list_of_images)))).transpose(2,0,1)

res = stack_images_rows_with_pad(image_batch)

for im in rez:
    print(im.shape)