I have a 3D numpy array of zeros, with dimensions CxHxW (in this example, C=4, H=2, and W=3):
JavaScript
x
9
1
A = np.array([[[0, 0, 0],
2
[0, 0, 0]],
3
[[0, 0, 0],
4
[0, 0, 0]]
5
[[0, 0, 0],
6
[0, 0, 0]]
7
[[0, 0, 0],
8
[0, 0, 0]]])
9
I also have a 2D array of indices, with dimensions HxW, such that every value in the array is a valid index between [0, C-1]
JavaScript
1
3
1
B = np.array([[2, 3, 0],
2
[3, 1, 2]])
3
Is there a fast way, using vectorization, to modify array A such that A[B[i][j]][i][j] = 1, for all valid i, j?
JavaScript
1
9
1
A = np.array([[[0, 0, 1],
2
[0, 0, 0]],
3
[[0, 0, 0],
4
[0, 1, 0]]
5
[[1, 0, 0],
6
[0, 0, 1]]
7
[[0, 1, 0],
8
[1, 0, 0]]])
9
Thank you!
Advertisement
Answer
It seems like you are looking for put_along_axis:
JavaScript
1
2
1
np.put_along_axis(A, B[None, ], 1, 0)
2
Note that the second argument is required to have the same number of dimensions as the first, which is why B[None,...]
is used instead of B
.