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.
To do this,
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)