Is there an easy way to index a numpy multidimensional array along the last dimension, using an array of indices? For example, take an array a
of shape (10, 10, 20)
. Let's assume I have an array of indices b
, of shape (10, 10)
so that the result would be c[i, j] = a[i, j, b[i, j]]
.
I've tried the following example:
a = np.ones((10, 10, 20))
b = np.tile(np.arange(10) + 10, (10, 1))
c = a[b]
However, this doesn't work because it then tries to index like a[b[i, j], b[i, j]]
, which is not the same as a[i, j, b[i, j]]
. And so on. Is there an easy way to do this without resorting to a loop?