Indexing into the last axis of a 3D array with another 3D array
<p>if i have an array <strong>x</strong>, which value is as follow with shape <strong>(2,3,4)</strong>:</p>

<pre><code>array([[[ 0.15845319,  0.57808432,  0.05638804,  0.56237656],
        [ 0.73164208,  0.80562342,  0.64561066,  0.15397456],
        [ 0.34734043,  0.88063258,  0.4863103 ,  0.09881028]],

       [[ 0.35823078,  0.71260357,  0.49410944,  0.94909165],
        [ 0.02730397,  0.67890392,  0.74340148,  0.47434223],
        [ 0.02494292,  0.59827256,  0.20550867,  0.30859339]]])
</code></pre>

<p>and i have an index array <strong>y</strong>, which shape is <strong>(2, 3, 3)</strong>, and the value is:</p>

<pre><code>array([[[0, 2, 2],
        [2, 0, 2],
        [0, 0, 2]],

       [[1, 2, 1],
        [1, 1, 1],
        [1, 2, 2]]])
</code></pre>

<p>so i could use <strong>x[0,0,y[0][0]]</strong> to index the array <strong>x</strong>, and it will generate the output as follow:</p>

<pre><code>array([ 0.15845319,  0.05638804,  0.05638804])
</code></pre>

<p>my question is: is there any simple way to do this? i had already tried with
<strong>x[y]</strong>, it did not work.</p>

<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing" rel="nofollow"><code>fancy-indexing</code></a> -</p>

<pre><code>m,n = y.shape[:2]
out = x[np.arange(m)[:,None,None],np.arange(n)[:,None],y]
</code></pre>

python arrays numpy