Python numpy insert 2d array into bigger 2d array on given posiiton

Question:

Lets say you have a Numpy 2d-array:

import numpy as np
big = np.zeros((4, 4))
>>> big
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])
   

Another 2d array, smaller or equal in length on both axis:

small = np.array([
    [1, 2],
    [3, 4]
])

You now want to override some values of big with the values of small, starting with the upper left corner of small -> small[0][0] on a starting point in big.

e.g.:

import numpy as np

big = np.zeros((4, 4))

small = np.array([
    [1, 2],
    [3, 4]
])

def insert_at(big_arr, pos, to_insert_arr):
    return [...]


result = insert_at(big, (1, 2), small)
>>> result
array([[0., 0., 0., 0.],
       [0., 0., 1., 2.],
       [0., 0., 3., 4.],
       [0., 0., 0., 0.]])

I expected an numpy function for that but couldn’t find one.

Asked By: Fabian

||

Answers:

To do this,

  1. Make sure the position will not make the small matrix exceed the boundaries of the big matrix
  2. Just subset the part of the big matrix at the position with the small matrix.
import numpy as np

big = np.zeros((4, 4))

small = np.array([
    [1, 2],
    [3, 4]
])


def insert_at(big_arr, pos, to_insert_arr):
    x1 = pos[0]
    y1 = pos[1]
    x2 = x1 + to_insert_arr.shape[0]
    y2 = y1 + to_insert_arr.shape[1]

    assert x2 <= big_arr.shape[0], "the position will make the small matrix exceed the boundaries at x"
    assert y2 <= big_arr.shape[1], "the position will make the small matrix exceed the boundaries at y"

    big_arr[x1:x2, y1:y2] = to_insert_arr

    return big_arr


result = insert_at(big, (1, 1), small)
print(result)
Answered By: Elmahy