[英]Python append matrix along given dimension
在具有200次迭代的循环中,我有一个临时输出temp.shape = (1L, 2L, 128L, 30L, 3L)
。
我想将这些temp
矩阵中的几个沿第5维( 3L
)附加在一起,
这样总输出为Total.shape = (1L, 2L, 128L, 30L, 600L)
我相信我需要使用np.stack
,但是我似乎无法使其正常工作。
例如,我尝试:
Total = np.stack((Total, temp), axis=5)
,
但这在几次迭代后失败了。
np.stack
在这里不合适,因为它沿新轴附加数组。 您正在寻找的是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)
我觉得也应该有一种使用生成器的方法(它甚至可以避免构造列表),但是我不得不承认我现在无法运行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.