从系列/列中找到第一个元素的索引(例如"True") [英] Finding the index of the first element (e.g "True") from a series/column
问题描述
如何找到序列或列中某个元素(例如"True")的索引?
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
然后创建一个布尔数据序列,其中的数据为False,直到第一个实例为True.然后如何找到数据点的索引?
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?
有更好的方法吗?
推荐答案
使用 idxmax
查找最大值的第一个实例.在这种情况下, True
是最大值.
Use idxmax
to find the first instance of the maximum value. In this case, True
is the maximum value.
df['Force'].lt(event).idxmax()
考虑示例 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
Force
的第一个实例小于 3
的情况是在索引'd'
处.
The first instance of Force
being less than 3
is at index 'd'
.
df['Force'].lt(3).idxmax()
'd'
请注意,如果 Force
的值均不小于3,则最大值将为 False
,而第一个实例将是第一个实例.
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.
还考虑替代方法 argmax
df.Force.lt(3).values.argmax()
3
它返回最大值的第一个实例的位置.然后,您可以使用它来找到相应的 index
值:
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'
此外,将来, argmax
将成为Series方法.
Also, in the future, argmax
will be a Series method.
这篇关于从系列/列中找到第一个元素的索引(例如"True")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!