You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取DataFrame中Stages列里Stage 2首次出现的索引?

获取DataFrame中指定值首次出现的索引

针对你提供的DataFrame,要获取Stages列里Stage 2首次出现的索引,下面是几种实用的实现方式:

方法一:利用idxmax()

通过布尔筛选生成一个布尔序列,idxmax()会返回第一个True对应的索引值,这是效率较高的方式:

first_stage2_idx = (df['Stages'] == 'Stage 2').idxmax()
print(first_stage2_idx)  # 输出:1

方法二:利用argmax()

和idxmax()逻辑类似,argmax()返回布尔序列中第一个True的整数位置,在默认整数索引的场景下结果一致:

first_stage2_idx = (df['Stages'] == 'Stage 2').argmax()
print(first_stage2_idx)  # 输出:1

方法三:筛选后取首个索引

先筛选出所有匹配Stage 2的行,再取第一个索引,这种方式可以处理没有匹配项的情况:

matching_indices = df[df['Stages'] == 'Stage 2'].index
if not matching_indices.empty:
    first_stage2_idx = matching_indices[0]
    print(first_stage2_idx)  # 输出:1
else:
    print("未找到匹配的Stage 2")

内容的提问来源于stack exchange,提问作者Amelia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:25:54