pandas – find first occurrence

idxmax and argmax will return the position of the maximal value or the first position if the maximal value occurs more than once.

use idxmax on df.A.ne('a')

df.A.ne('a').idxmax()

3

or the numpy equivalent

(df.A.values != 'a').argmax()

3

However, if A has already been sorted, then we can use searchsorted

df.A.searchsorted('a', side="right")

array([3])

Or the numpy equivalent

df.A.values.searchsorted('a', side="right")

3

Leave a Comment