numpy 重复给定的数组以获得更复杂的形状

ehxuflar  于 2023-04-21  发布在  其他
关注(0)|答案(3)|浏览(160)

我想创建一个形状为(3, 3, 4)的数组。用于填充数组的数据已给出。
我的解决方案现在工作得很好,但感觉我错过了一个 numpy 教训。我不想一遍又一遍地做多个.repeat()

start = np.linspace(start=10, stop=40, num=4)
arr = np.repeat([start], 3, axis=0)
arr = np.repeat([arr], 3, axis=0)
arr

# output
array([[[10., 20., 30., 40.],
        [10., 20., 30., 40.],
        [10., 20., 30., 40.]],

       [[10., 20., 30., 40.],
        [10., 20., 30., 40.],
        [10., 20., 30., 40.]],

       [[10., 20., 30., 40.],
        [10., 20., 30., 40.],
        [10., 20., 30., 40.]]])
pbpqsu0x

pbpqsu0x1#

您提到的数组可以通过首先使用np.linspace()创建一个1D数组,然后使用np.tile()以所需的形状重复该数组来创建。
以下是更新的代码:

import numpy as np

start = np.linspace(start=10, stop=40, num=4)
arr = np.tile(start, (3, 3, 1))

print(arr)

我认为这是创建所需数组的更简洁的方法。
下面是你得到的输出:

[[[10. 20. 30. 40.]
  [10. 20. 30. 40.]
  [10. 20. 30. 40.]]

 [[10. 20. 30. 40.]
  [10. 20. 30. 40.]
  [10. 20. 30. 40.]]

 [[10. 20. 30. 40.]
  [10. 20. 30. 40.]
  [10. 20. 30. 40.]]]

在上面的代码中,np.tile()用于以(3, 3, 1)的形状重复start数组。添加最后一个维度(1)以匹配(3, 3, 4)所需的形状并正确分配值。

ni65a41a

ni65a41a2#

有多种方法可以创建所需的数组,但请记住,由于broadcasting,在许多情况下,数组可以自动像(3, 3, 4)形状的数组一样运行。
在这种情况下,我认为创建所需数组的最优雅方法是通过np.broadcast_to“强制”广播:

import numpy as np

start = np.linspace(start=10, stop=40, num=4)

out = np.broadcast_to(start, (3, 3, 4))

输出:

array([[[10., 20., 30., 40.],
        [10., 20., 30., 40.],
        [10., 20., 30., 40.]],

       [[10., 20., 30., 40.],
        [10., 20., 30., 40.],
        [10., 20., 30., 40.]],

       [[10., 20., 30., 40.],
        [10., 20., 30., 40.],
        [10., 20., 30., 40.]]])
rt4zxlrg

rt4zxlrg3#

除了tile之外的另一个选项是使用broadcast_to

start = np.linspace(start=10, stop=40, num=4)
arr = np.broadcast_to(start,(3,3,4))

导致期望的结果。

相关问题