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

如何在while/for循环中忽略IndexError并定位表格指定值行索引

解决查找指定内容行索引的IndexError问题

原代码遍历列时,若当前列未匹配到"1.2 Information",执行index[0]会触发IndexError——空索引对象无法获取第0个元素。通过判断匹配结果是否为空,结合continue跳过无匹配列即可解决,修改后的代码如下:

ind = None
cols = list(df.columns)
while ind is None:
    for col in cols:
        # 获取当前列匹配目标内容的行,na=False避免空值报错
        matched_rows = df[df[col].str.contains('^1.2 Information', na=False)]
        # 有匹配行则提取索引并退出循环
        if not matched_rows.empty:
            ind = int(matched_rows.index[0])
            break
        # 无匹配则跳过当前列,继续遍历下一列
        continue

关键修改说明:

  • 将ind初始化为None,更适合判断是否找到目标索引
  • 给str.contains添加na=False,避免单元格空值(NaN)引发的异常
  • 每次遍历列时先检查匹配结果是否为空,为空则用continue跳过当前列
  • 找到匹配行后立即break退出列循环,减少不必要的遍历

简化版(无需外层while循环):

因目标值唯一,遍历所有列一次即可找到结果,可去掉外层while循环:

ind = None
cols = list(df.columns)
for col in cols:
    matched_rows = df[df[col].str.contains('^1.2 Information', na=False)]
    if not matched_rows.empty:
        ind = int(matched_rows.index[0])
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:22:06