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:
JavaScript
x
2
1
s = pd.Series([False, False, True, True, False, False])
2
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
:
JavaScript
1
3
1
s = pd.Series([False, False, True, True, False, False])
2
s.where(s).last_valid_index()
3
Output:
JavaScript
1
2
1
3
2
Using @user3483203 example
JavaScript
1
3
1
s = pd.Series(['dog', 'cat', 'fish', 'cat', 'dog', 'horse'], index=[*'abcdef'])
2
s.where(s=='cat').last_valid_index()
3
Output
JavaScript
1
2
1
'd'
2