【发布时间】:2023-03-24 06:55:02
【问题描述】:
我有一个整数的二维数组 MxN,我想将数组扩展为 (BM)x(BN) 其中 B 是方块边的长度,因此输入数组的每个元素在最终数组中作为 BxB 块重复。下面是一个带有嵌套 for 循环的示例。有更快/内置的方式吗?
import numpy as np
a = np.arange(9).reshape([3,3]) # input array - 3x3
B=2. # block size - 2
A = np.zeros([a.shape[0]*B,a.shape[1]*B]) # output array - 6x6
# Loop, filling A with tiled values of a at each index
for i,l in enumerate(a): # lines in a
for j,aij in enumerate(l): # a[i,j]
A[B*i:B*(i+1),B*j:B*(j+1)] = aij
结果...
a= [[0 1 2]
[3 4 5]
[6 7 8]]
A = [[ 0. 0. 1. 1. 2. 2.]
[ 0. 0. 1. 1. 2. 2.]
[ 3. 3. 4. 4. 5. 5.]
[ 3. 3. 4. 4. 5. 5.]
[ 6. 6. 7. 7. 8. 8.]
[ 6. 6. 7. 7. 8. 8.]]
【问题讨论】: