我有一个如下数组:
arr = np.arange(2*1*15).reshape(2, 1, 15)
现在,我如何扩展此数组以形成(2, 10, 15)
的形状。要填充这些值,可以使用与原始数组的(1, 15)
部分相同的值(例如,从最后两个维度开始)。
答案 0 :(得分:1)
您可以使用numpy.repeat
沿第二个轴复制值:
np.repeat(arr, 10, axis=1).shape
# (2, 10, 15)
答案 1 :(得分:1)
与此同时,我发现numpy.broadcast_to也可以完成这项工作。
作为一个人为的小例子:
In [8]: np.broadcast_to(arr, (2, 5, 15))
Out[8]:
array([[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]],
[[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]])
性能注意事项:计时后,我发现numpy.broadcast_to
大约是。与numpy.repeat
相比,快 40倍。
reason for this performance gain是因为:
之所以更快,是因为它创建了一个只读的数据视图,其中包含许多指向相同内存位置的元素。如果复制结果,则性能大致相同。如果您不需要编辑最终结果,则可以大大提高性能