I'm working on a code and a question just pop up in my head. So basically I have a 3D numpy array with shape
(2, 5, 5) and also a 2D numpy array with shape (2, 4) (this is just an example, the arrays, can be much bigger). What I need is to replace the values of 1 in the subarrays of the 3D array (slice [:, 2:, 2:] ) by the values in my 2D array. I thought about getting the index from the values I want to change (the ones) in the 3D array and then use a for loop in the 2D array to iterate through the values but I'm not sure if it's efficient way and also I'm getting an error.
import numpy as np
arr = np.array([[[0., 1., 43., 25., 21.],
[0., 0., 0., 0., 0.],
[0., 43., 0., 1., 0.],
[0., 43., 1., 0., 1.],
[0., 45., 0., 1., 0.]],
[[0., 1., 38., 29., 46.],
[0., 0., 0., 0., 0.],
[0., 32., 0., 0., 1.],
[0., 26., 0., 0., 1.],
[0., 30., 1., 1., 0.]]])
values = [[2, 3, 1, 4],
[4, 1, 5, 9]]
indexes = np.argwhere(newarr[:, 2:, 2:] == 1) + [0, 2, 2]
# indexes = [[0 2 3]
# [0 3 2]
# [0 3 4]
# [0 4 3]
# [1 2 4]
# [1 3 4]
# [1 4 2]
# [1 4 3]]
for i in values:
arr[indexes] == i
#Error
#index 2 is out of bounds for axis 0 with size 2
My desired output should be
newarr = [[[0., 1., 43., 25., 21.],
[0., 0., 0., 0., 0.],
[0., 43., 0., 2., 0.],
[0., 43., 3., 0., 1.],
[0., 45., 0., 4., 0.]],
[[0., 1., 38., 29., 46.],
[0., 0., 0., 0., 0.],
[0., 32., 0., 0., 4.],
[0., 26., 0., 0., 1.],
[0., 30., 5., 9., 0.]]])
I think there should be a more efficient using only numpy, but I can't see how to do this, so any help will be appreciated, thank you!