<p>为了得到最后一个索引,我们可以沿所有轴翻转顺序,然后对匹配项使用<code>np.argmax()</code>。翻转的思想是利用有效的<code>np.argmax</code>来获得第一个匹配索引。</p>
<p>因此,实施将是-</p>
<pre><code>def last_match_index(a, value):
idx = np.array(np.unravel_index(((a==value)[::-1,::-1,::-1]).argmax(), a.shape))
return a.shape - idx - 1
</code></pre>
<p>运行时测试-</p>
<pre><code>In [180]: a = np.random.randint(0,10,(100,100,100))
In [181]: last_match_index(a,7)
Out[181]: array([99, 99, 89])
# @waterboy5281's argwhere soln
In [182]: np.argwhere(a==7)[-1]
Out[182]: array([99, 99, 89])
In [183]: %timeit np.argwhere(a==7)[-1]
100 loops, best of 3: 4.67 ms per loop
In [184]: %timeit last_match_index(a,7)
1000 loops, best of 3: 861 µs per loop
</code></pre>
<p>如果你想得到一个轴上的最后一个索引,比如说<code>axis=0</code>,然后沿着两个轴迭代,比如说最后两个轴,我们可以采用相同的方法-</p>
<pre><code>a.shape[0] - (a==7)[::-1,:,:].argmax(0) - 1
</code></pre>
<p>样本运行-</p>
<pre><code>In [158]: a = np.random.randint(4,8,(100,100,100))
...: m,n,r = a.shape
...: out = np.full((n,r),np.nan)
...: for i in range(n):
...: for j in range(r):
...: out[i,j] = np.argwhere(a[:,i,j]==7)[-1]
...:
In [159]: out1 = a.shape[0] - (a==7)[::-1,:,:].argmax(0) - 1
In [160]: np.allclose(out, out1)
Out[160]: True
</code></pre>