通过重复2D numpy数组中的值来创建4D numpy数组

我有一个2D numpy数组,比如说array1有值. array1的尺寸为2×4.我想创建一个尺寸为20x20x2x4的4D numpy数组array2,我希望复制数组array1来获取这个数组.

也就是说,如果array1是

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

我想要

array2[0, 0] = array1
array2[0, 1] = array1
array2[0, 2] = array1
array2[0, 3] = array1
# etc.

我怎样才能做到这一点?

最佳答案 一种初始化方法 –

array2 = np.empty((20,20) + array1.shape,dtype=array1.dtype)
array2[:] = array1

运行时测试 –

In [400]: array1 = np.arange(1,9).reshape(2,4)

In [401]: array1
Out[401]: 
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

# @MSeifert's soln
In [402]: %timeit np.tile(array1, (20, 20, 1, 1))
100000 loops, best of 3: 8.01 µs per loop

# Proposed soln in this post
In [403]: %timeit initialization_based(array1)
100000 loops, best of 3: 4.11 µs per loop

# @MSeifert's soln for READONLY-view
In [406]: %timeit np.broadcast_to(array1, (20, 20, 2, 4))
100000 loops, best of 3: 2.78 µs per loop
点赞