为了得到最后一个索引,我们可以沿所有轴翻转顺序,然后对匹配项使用np.argmax()。翻转的思想是利用有效的np.argmax来获得第一个匹配索引。
因此,实施将是-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
运行时测试-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
如果你想得到一个轴上的最后一个索引,比如说axis=0,然后沿着两个轴迭代,比如说最后两个轴,我们可以采用相同的方法-a.shape[0] - (a==7)[::-1,:,:].argmax(0) - 1
样本运行-In [158]: a = np.random