I have a 3D array a with shape (m, n, p) and a 2D array idx with shape (m, n). I want all elements in a where the last axis index is smaller than the corresponding element in idx to be set to 0.
The following code works. My question is : is there a more efficient approach?
a = np.array([[[1, 2, 3],
[4, 5, 6]],
[[7, 8, 9],
[10, 11, 12]],
[[21, 22, 23],
[25, 26, 27]]])
idx = np.array([[2, 1],
[0, 1],
[1, 1]])
for (i, j), val in np.ndenumerate(idx):
a[i, j, :val] = 0
The result is
array([[[ 0, 0, 3],
[ 0, 5, 6]],
[[ 7, 8, 9],
[ 0, 11, 12]],
[[ 0, 22, 23],
[ 0, 26, 27]]])