Skip to content
Advertisement

Numpy assignment of 3D array values using 2D index array

I have a 3D numpy array of zeros, with dimensions CxHxW (in this example, C=4, H=2, and W=3):

JavaScript

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

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

Thank you!

Advertisement

Answer

It seems like you are looking for put_along_axis:

JavaScript

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.

Advertisement