将预定义的数组插入到大数组上,并迭代地移动较小数组的位置



我想将一个大小为 2*2 的数组填充零到一个更大的数组中。此外,我想迭代地将零数组的位置从左到右,从上到下移动。

zero_array =[0 0
0 0]
large_array =[ 1  2  3  4
5  6  7  8
9 10 11 12
13 14 15 16]

所需结果:

Ist iteration
[ 0  0  3  4
0  0  7  8
9 10 11 12
13 14 15 16]
2nd iteration
[ 1  0  0  4
5  0  0  8
9 10 11 12
13 14 15 16]
3rd iteration 
[ 1  2  0  0
5  6  0  0
9 10 11 12
13 14 15 16]
4th Iteration 
[ 1  2  3  4
0  0  7  8
0  0 11 12
13 14 15 16]

等等...

import copy
import numpy as np
la=np.array(<insert array here>)
za=np.zeros((2,2))
ma=copy.deepcopy(la)
for i in range(len(la)-len(za)+1):
for j in range(len(la)-len(za)+1):
la=copy.deepcopy(ma)
la[i:i+len(za),j:j+len(za)]=za
print la
#la=large array
#za=zero array

在较大的数组中插入较小的数组非常容易,您只需要找出应该插入的位置(例如,通过左上角的坐标(:

def insert_array(bigger_arr, smaller_arr, pos):
out = np.array(bigger_arr, copy=True) 
if bigger_arr.ndim != smaller_arr.ndim or bigger_arr.ndim != len(pos):
raise ValueError('incompatible dimension')
slicer = [slice(p, p+extend) for p, extend in zip(pos, smaller_arr.shape)]
out[tuple(slicer)] = smaller_arr
return out
>>> insert_array(np.arange(16).reshape(4, 4), np.zeros((2, 2)), pos=(0, 0))
array([[ 0,  0,  2,  3],
[ 0,  0,  6,  7],
[ 8,  9, 10, 11],
[12, 13, 14, 15]])

然后剩下的就是循环计算坐标。这可以通过生成器功能轻松完成:

from itertools import product
def looping_inserting(bigger_arr, smaller_arr):
for startpos in product(*[range(big_dim - small_dim + 1) 
for big_dim, small_dim 
in zip(bigger_arr.shape, smaller_arr.shape)]):
yield insert_array(bigger_arr, smaller_arr, startpos)
for newarr in looping_inserting(np.arange(1, 17).reshape(4, 4), np.zeros((2, 2))):
print(newarr)

其中打印:

[
[ 0 0 3 4]  [ 0  0  7  8]  [ 9 10 11 12]  [13 14 15 16]] [[ 1  0  0  4]  [ 5  0  0  8]  [ 9 10 11 12]  [13 14 15 16]] [[ 1  2  0  0]  [ 5  6  0  0]  [ 9 10 11 12]  [13 14 15 16]] [[ 1  2  3  4]  [ 0  0  7  8]  [ 0  0 11 12]  [13 14 15 16]] [[ 1  2  3  4]  [ 5  0  0  8]  [ 9  0  0 12]  [13 14 15 16]] [[ 1  2  3  4]  [ 5  6  0  0]  [ 9 10  0  0]  [13 14 15 16]] [[ 1  2  3  4]  [ 5  6  7  8]  [ 0  0 11 12]  [ 0  0 15 16]] [[ 1  2  3  4]  [ 5  6  7  8]  [ 9  0  0 12]  [13  0  0 16]] [[ 1  2  3  4]  [ 5  6  7  8]  [ 9 10  0  0]  [13 14 0 0]]

如果您只处理 2D 数组,则可以简化很多代码,也许这也更好理解:

from itertools import product
def insert_array(bigger_arr, smaller_arr, pos):
out = np.array(bigger_arr, copy=True) 
if bigger_arr.ndim != smaller_arr.ndim or bigger_arr.ndim != len(pos):
raise ValueError('incompatible dimension')
out[pos[0]: pos[0] + smaller_arr.shape[0],
pos[1]: pos[1] + smaller_arr.shape[1]] = smaller_arr
return out
def looping_inserting(bigger_arr, smaller_arr):
for pos0 in range(bigger_arr.shape[0] - smaller_arr.shape[0] + 1):
for pos1 in range(bigger_arr.shape[1] - smaller_arr.shape[1] + 1):
yield insert_array(bigger_arr, smaller_arr, (pos0, pos1))
for newarr in looping_inserting(np.arange(1, 17).reshape(4, 4), np.zeros((2, 2))):
print(newarr)

最新更新