重复2D NumPy数组N次

时间:2018-12-06 02:01:40

标签: python arrays numpy

我需要通过复制源数组将32X32形状的2d数组扩充(复制)为32X32X3形状的3d数组。我该如何以最好的方式做到这一点?

下面是源数组和预期数组的示例。我需要将此逻辑应用到更大范围的应用程序中

源数组:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

预期数组:

array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]])

3 个答案:

答案 0 :(得分:4)

通过我的测试,np.repeatnp.tile快一点:

X = np.repeat(arr[None,:], 3, axis=0)

或者,使用np.concatenate

X = np.concatenate([[arr]] * 3, axis=0)

arr = np.arange(10000 * 1000).reshape(10000, 1000)

%timeit np.repeat(arr[None,:], 3, axis=0)
%timeit np.tile(arr, (3, 1, 1))
%timeit np.concatenate([[arr]] * 3, axis=0)
# Read-only, array cannot be modified.
%timeit np.broadcast_to(arr, (3, *arr.shape))
# Creating copy of the above.
%timeit np.broadcast_to(arr, (3, *arr.shape)).copy()

170 ms ± 3.82 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
187 ms ± 3.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
243 ms ± 3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
10.9 µs ± 218 ns per loop (mean ± std. dev. of 7 runs, 100000 loops 
189 ms ± 2.45 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)each) 

np.array_equals(np.repeat(arr[None,:], 3, axis=0), 
                np.tile(arr, (3, 1, 1))
True

答案 1 :(得分:2)

如果您不需要修改结果,请使用broadcast_to

np.broadcast_to(arr, (3, *arr.shape))

使用@coldspeed的答案进行验证:

arr = np.arange(10000 * 1000).reshape(10000, 1000)
X = np.repeat(arr[None,:], 3, axis=0)
broadcast_x = np.broadcast_to(arr, (3, *arr.shape))

np.array_equal(X, broadcast_x)

True

如果需要进行修改,则可以对结果调用copy(),就结果而言,该结果应接近repeattile速度。

答案 2 :(得分:1)

听起来像np.tile的工作:

In [101]: np.tile(A, (3,1,1))
Out[101]: 
array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]])

第二个参数指定每个维度上的副本数。