获取DataFrame中特定值位置并比较后续值的优化方案
通用实现方案
直接通过提取目标值的所有索引批量遍历处理,不需要手动硬编码索引,适配任意数量的目标值场景。
完整代码实现
import pandas as pd # 构造示例DataFrame,可替换为你的实际数据 df = pd.DataFrame({'Value': [1, 2, 1, 2, 3, 2]}) # 自定义目标查找值 target_val = 2 # 提取所有目标值对应的行索引 target_index_list = df[df['Value'] == target_val].index for idx in target_index_list: # 边界判断:当前索引是最后一行 if idx == df.index[-1]: print(f"{target_val} is the last number") continue # 取当前行的下一行值 next_value = df['Value'].iloc[idx + 1] if target_val > next_value: print(f"{target_val} is bigger") elif target_val < next_value: print(f"{target_val} is smaller")
输出结果
运行上述代码会直接输出你需要的预期结果:
2 is bigger 2 is smaller 2 is the last number
方案优势
- 无需手动硬编码索引,自动适配任意数量的目标值场景
- 自动处理目标值出现在最后一行的边界情况
- 可直接修改
target_val变量适配其他目标值的查找需求
内容的提问来源于stack exchange,提问作者AchillesDay
相关产品推荐
相关产品推荐

