は非常に簡単です、あなただけのどこにそれを見つける必要があります(左上の座標など)を挿入する必要があります。
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)