首页 > 解决方案 > 如何有效地访问熊猫中满足条件的第一次和最后一次出现索引

问题描述

这个想法是访问满足 Pandas 条件的第一个和最后一个出现索引。

下面的代码可以达到上述目的。但是,我只是好奇是否有更有效的方法来达到相同的结果

从示例和代码来看,预计会得到第二行和第五行作为最终结果。

df = pd.DataFrame({'A':[1,2,3,4,5,10,2],
               'B' :[1,2,3,4,5,110,2]})

IndexGreaterThan=df[df['A'].gt(2)].index.tolist() 

Voltage_FirstAboveThrshold=df.at[IndexGreaterThan[0],'A']
Time_FirstAboveThrshold=df.at[IndexGreaterThan[0],'B']

Voltage_LastAboveThrshold=df.at[IndexGreaterThan[-1],'A']
Time_LastAboveThrshold=df.at[IndexGreaterThan[-1],'B']

然后

print(Voltage_FirstAboveThrshold,Time_FirstAboveThrshold)
print(Voltage_LastAboveThrshold,Time_LastAboveThrshold)

输出

3 3
10 110

感谢任何建议

标签: pythonpandasdataframeindexing

解决方案


尝试这样的事情:

df[df.A.gt(2)].iloc[[0,-1]]

细节:

  • df[df.A.gt(2)]选择A > 2 的行。
  • .iloc[[0,-1]]选择第一行和最后一行(从上面选择的)。

推荐阅读