I have a 2d array arr. Here’s an example:
>> arr
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
I also have a 2d array of indices indices (with indices.shape[0] == arr.shape[0], and indices.shape[1] <= arr.shape[1]). Here is an example:
>>> indices
array([[0, 1],
[1, 2],
[0, 2],
[0, 2]])
Now, I want to set some elements of arr to -1. Specifically, on the first row of arr, the first and the second element should be set to -1 (because indices[0] == [0, 1]). On the second row of arr, the second and the third element should be set to -1 (because indices[1] == [1, 2]). And so on.
This would be the expected result:
array([[ -1, -1, 2],
[ 3, -1, -1],
[ -1, 7, -1],
[ -1, 10, -1]])
I tried to look for existing solutions but I haven’t found any. Any suggestion?
>Solution :
Broadcast assignment:
>>> arr[np.arange(4)[:, None], indices] = -1
>>> arr
array([[-1, -1, 2],
[ 3, -1, -1],
[-1, 7, -1],
[-1, 10, -1]])