python - 如何有效地访问熊猫中满足条件的第一次和最后一次出现索引
问题描述
这个想法是访问满足 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
感谢任何建议
解决方案
尝试这样的事情:
df[df.A.gt(2)].iloc[[0,-1]]
细节:
df[df.A.gt(2)]
选择A > 2 的行。.iloc[[0,-1]]
选择第一行和最后一行(从上面选择的)。
推荐阅读
- python - ImportError:没有名为 playsound 的模块
- excel - VBA - 在数据间隙之间插入合并行
- android - 在启动活动中加载数据并将该数据或 ViewModel 共享到 MVVM 中的下一个活动
- linux - 如何确定 ls 命令输出是文件还是目录 Bash
- python - Pyomo 的线性代数
- sql - Paginate grouped query results with limit per page
- authentication - 我的身份验证问题是否与双跳问题有关?
- java - 使用 PACT 时如何在 HttpTarget 中传递标头
- sql-server - 具有多个 if 语句时的 SQL 过程行为
- python - Debian AWS 自动启动脚本