Q:

Moving a 2D numpy subarray efficiently

I have a numpy array that represents a greyscale image, such as
image = numpy.array([
    [.0, .0, .0, .0, .1, .3, .5, .0],
    [.0, .0, .0, .0, .4, .4, .6, .0],
    [.0, .0, .0, .0, .3, .3, .7, .0],
    [.0, .0, .0, .0, .0, .0, .0, .0],
    [.0, .0, .0, .0, .0, .0, .0, .0],
    [.0, .0, .0, .0, .0, .0, .0, .0],
])

I would like to move a sub-array to a new location, filling the values left behind with some constant (say 0.0). For example, moving the 3x3 sub-array from center position of (1, 5) to center position (3, 3) would result in:
numpy.array([
    [.0, .0, .0, .0, .0, .0, .0, .0],
    [.0, .0, .0, .0, .0, .0, .0, .0],
    [.0, .0, .1, .3, .5, .0, .0, .0],
    [.0, .0, .4, .4, .6, .0, .0, .0],
    [.0, .0, .3, .3, .7, .0, .0, .0],
    [.0, .0, .0, .0, .0, .0, .0, .0],
])

Is there an efficient way to perform such a move?

A:

Since you know the starting index of where you want to move from and move to, we can use np.zeros_like and numpy indexing:
h = w = 3
sub = image[0:0+w,4:4+h]
out = np.zeros_like(image)

Then assign:
out[2:2+w, 2:2+h] = sub

Output:
array([[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
       [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
       [0. , 0. , 0.1, 0.3, 0.5, 0. , 0. , 0. ],
       [0. , 0. , 0.4, 0.4, 0.6, 0. , 0. , 0. ],
       [0. , 0. , 0.3, 0.3, 0.7, 0. , 0. , 0. ],
       [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]])

