gpt4 book ai didi

python - 如何有效访问 Pandas 中满足条件的第一个和最后一个出现的索引

转载 作者:行者123 更新时间:2023-12-01 00:32:25 25 4
gpt4 key购买 nike

这个想法是访问 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

感谢任何建议

最佳答案

使用

  • .iloc - 纯粹基于整数位置的索引,用于按位置选择。
<小时/>
import pandas as pd
df = pd.DataFrame({'A':[1,2,3,4,5,10,2],
'B' :[1,2,3,4,5,110,2]})

df = df[df['A'].gt(2)]
df2 = df.iloc[[0, -1]]
print(df2)

A B
2 3 3
5 10 110

关于python - 如何有效访问 Pandas 中满足条件的第一个和最后一个出现的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58079891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com