Largest index where condition is true, without using argwhere

Viewed 28

I want to get the largest index where a condition is true, e.g.:

import numpy as np

a = np.arange(10, 0, -1)
i = np.max(np.argwhere(a > 5).ravel())
print(i)

which gives 4.

But I want to do this on a very large array, where np.argwhere is simply too costly.

How can I do this without allocating a (large) array, i.e. without np.argwhere?

1 Answers

Use argmax on flipped mask that gives us first index and thus essentially last index in original order -

len(a)-np.argmax((a>5)[::-1])-1
Related