How to find last occurence index matching a certain value in a Pandas Series?

You can use np.argmax on your reversed Series if you are looking in a boolean array:

>>> len(s) - np.argmax(s[::-1].values) - 1
3

If you are looking for another value, just convert it to a boolean array using ==

Here's an example looking for the last occurence of dog:

>>> s = pd.Series(['dog', 'cat', 'fish', 'cat', 'dog', 'horse'])
>>> len(s) - np.argmax(s[::-1].values=='dog') - 1
4

However, this will give you a numeric index. If your series has a custom index it will not return that.


Using nonzero

s.nonzero()[0][-1]
Out[66]: 3

Use last_valid_index:

s = pd.Series([False, False, True, True, False, False])
s.where(s).last_valid_index()

Output:

3

Using @user3483203 example

s = pd.Series(['dog', 'cat', 'fish', 'cat', 'dog', 'horse'], index=[*'abcdef'])
s.where(s=='cat').last_valid_index()

Output

'd'

Tags:

Python

Pandas