Index number nd array along the last dimension

Is there an easy way to index a numpy multidimensional array along the last dimension using an index array? For example, take an array of ashapes (10, 10, 20). Suppose I have an array of indexes b, forms (10, 10), so that the result is c[i, j] = a[i, j, b[i, j]].

I tried the following example:

a = np.ones((10, 10, 20))
b = np.tile(np.arange(10) + 10, (10, 1))
c = a[b]

However, this does not work, because then it tries to index as a[b[i, j], b[i, j]], which does not match a[i, j, b[i, j]]. Etc. Is there an easy way to do this without resorting to a loop?

+4
source share
1 answer

There are several ways to do this. Let some test data be generated first:

In [1]: a = np.random.rand(10, 10, 20)

In [2]: b = np.random.randint(20, size=(10,10))  # random integers in range 0..19

, - , - 0..9, meshgrid:

In [3]: i1, i0 = np.meshgrid(range(10), range(10), sparse=True)

In [4]: c = a[i0, i1, b]

, i0, i1 b 10x10. :

In [5]: all(c[i, j] == a[i, j, b[i, j]] for i in range(10) for j in range(10))
Out[5]: True

choose rollaxis:

# choose needs a sequence of length 20, so move last axis to front
In [22]: aa = np.rollaxis(a, -1)  

In [23]: c = np.choose(b, aa)

In [24]: all(c[i, j] == a[i, j, b[i, j]] for i in range(10) for j in range(10))
Out[24]: True
+4

All Articles