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?
To find the indexes of the specific value that match the given condition in Pandas dataframe we will use df['Subject'] to match the given values and index. values to find an index of matched value. The result shows us that rows 0,1,2 have the value 'Math' in the Subject column.
Pandas iloc is used to retrieve data by specifying its integer index. In python negative index starts from end therefore we can access the last element by specifying index to -1 instead of length-1 which will yield the same result.
We can count by using the value_counts() method. This function is used to count the values present in the entire dataframe and also count values in a particular column.
You can use a generator expression with next
and enumerate
:
s = pd.Series([False, False, True, True, False, False])
res = len(s) - next(idx for idx, val in enumerate(s[::-1], 1) if val) # 3
This will be more efficient for large series with a True
value towards the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With