Python沿给定维度附加矩阵

时间:2018-03-27 19:03:57

标签: python matrix multidimensional-array

在一个超过200次迭代的循环中,我有一个临时输出temp.shape = (1L, 2L, 128L, 30L, 3L)

我想在第五维(temp)上附加几个3L矩阵,

总输出为Total.shape = (1L, 2L, 128L, 30L, 600L)

我相信我需要使用np.stack,但我似乎无法让它正常工作。

例如,我尝试:

Total = np.stack((Total, temp), axis=5)

但经过几次迭代后失败了。

1 个答案:

答案 0 :(得分:1)

np.stack在这里不合适,因为它沿 new 轴附加数组。您要找的是np.concatenate。你可以称之为

total = np.concatenate((total, temp), axis=4)

但是,这实际上效率很低,因为每次调用concatenate都会创建一个新数组,复制所有内容。所以你会复制大约200次。更好的方法是首先收集列表中的所有temp数组:

list_of_temps = ...  # this contains the 200 (1, 2, 128, 30, 3) arrays
total = np.concatenate(list_of_temps, axis=4)

这样可以避免重复复制数组内容。可能更好的选择是在temp数组上放置一个生成器而不是列表,以避免创建list_of_temps

编辑:这就是它在上下文中的样子:现在说你正在做什么

total = np.empty((1, 2, 128, 30, 0))  # empty array to concatenate to
for ind in range(200):
    temp = however_you_get_the_temps()
    total = np.concatenate((total, temp), axis=4)

这应该更快:

list_of_temps = []
for ind in range(200):
    temp = however_you_get_the_temps()
    list_of_temps.append(temp)
total = np.concatenate(list_of_temps, axis=4)

我觉得应该有一种方法可以使用生成器(这可以避免构建列表),但我不得不承认我现在无法运行。

相关问题