如何通过迭代创建其他numpy数组的numpy数组?

时间:2020-01-27 02:50:18

标签: python arrays numpy multidimensional-array

我正在尝试创建一个numpy数组,其中每个元素都是一个(48,48)形状的numpy数组,本质上是一个很大的列表,我可以在该列表上进行遍历并每次检索不同的48x48数组。

for i in range(1):
    new_image = np.fromstring(train_np[i][1],dtype=int,sep=" ")
    new_image = new_image.reshape(48,48) #create the new 48x48 correctly

    image_train = np.stack([image_train,new_image]) #this line only works once

当range为1(仅运行一次)时,堆栈将返回预期的结果形状(2,48 48)。多次运行会产生收益

ValueError: all input arrays must have the same shape

在这种情况下,是否有比np.stack更好的操作?我想进行迭代,然后查看形状变为(2,48,48)->(3,48,48)->(4,48,48)...,依此类推。

1 个答案:

答案 0 :(得分:0)

numpy已针对大型并行计算进行了优化。它在设计时没有非常灵活的数据形状,因此,如果您不能对数据的形状进行硬编码,通常最好使用列表(灵活),然后在末尾调用numpy堆叠它们。

image_train = []

for i in range(1):
    new_image = np.fromstring(train_np[i][1],dtype=int,sep=" ")
    new_image = new_image.reshape(48,48) 
    image_train.append(new_image) 

image_train = np.stack(image_train)

也就是说,您可以为此使用np.concatenate,但这会非常缓慢且操作不当。