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?
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.
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.
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.
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