沿特定维度扩展数组

时间:2019-03-22 17:12:49

标签: numpy multidimensional-array reshape tensor numpy-ndarray

我有一个如下数组:

arr = np.arange(2*1*15).reshape(2, 1, 15)

现在,我如何扩展此数组以形成(2, 10, 15)的形状。要填充这些值,可以使用与原始数组的(1, 15)部分相同的值(例如,从最后两个维度开始)。

2 个答案:

答案 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是因为:

  

之所以更快,是因为它创建了一个只读的数据视图,其中包含许多指向相同内存位置的元素。如果复制结果,则性能大致相同。如果您不需要编辑最终结果,则可以大大提高性能