Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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?

like image 557
Johan Dettmar Avatar asked Sep 12 '18 21:09

Johan Dettmar


People also ask

How do you find the index of a particular value in a Dataframe?

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.

How do you get the last value in a pandas Series?

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.

How do you count occurrences of specific value in pandas column?

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.


1 Answers

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.

like image 106
jpp Avatar answered Sep 28 '22 05:09

jpp