Skip to content
Advertisement

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

How do I find the last occurrence index for a certain value in a Pandas Series?

For example, let’s say I have a Series that looks like follows:

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

And I want to find the last index for a True value (i.e. index 3), how would you go about it?

Advertisement

Answer

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'
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement