Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of the first element (e.g "True") from a series/column

How do I find the index of an element (e.g "True") in a series or a column?

For example I have a column, where I want to identify the first instance where an event occur. So I write it as

Variable = df["Force"] < event

This then creates a boolen series of Data where it is False, until the first instance it becomes True. How then do I find the index of data point?

Is there are better way?

like image 969
Sofyan Sahrom Avatar asked Feb 06 '18 01:02

Sofyan Sahrom


People also ask

How do you find the first element in a series?

Accessing the First Element The first element is at the index 0 position. So it is accessed by mentioning the index value in the series. We can use both 0 or the custom index to fetch the value.

How do I index a column in pandas series?

In order to set index to column in pandas DataFrame use reset_index() method. By using this you can also set single, multiple indexes to a column. If you are not aware by default, pandas adds an index to each row of the pandas DataFrame.


1 Answers

Use idxmax to find the first instance of the maximum value. In this case, True is the maximum value.

df['Force'].lt(event).idxmax()

Consider the sample df:

df = pd.DataFrame(dict(Force=[5, 4, 3, 2, 1]), list('abcde'))
df

   Force
a      5
b      4
c      3
d      2
e      1

The first instance of Force being less than 3 is at index 'd'.

df['Force'].lt(3).idxmax()
'd'

Be aware that if no value for Force is less than 3, then the maximum will be False and the first instance will be the first one.

Also consider the alternative argmax

df.Force.lt(3).values.argmax()
3

It returns the position of the first instance of maximal value. You can then use this to find the corresponding index value:

df.index[df.Force.lt(3).values.argmax()]
'd'

Also, in the future, argmax will be a Series method.

like image 133
piRSquared Avatar answered Oct 08 '22 12:10

piRSquared