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

Python打印列表有值但pop/索引访问时报空(Pandas读取Excel场景)

问题成因

  1. 代码缩进错误:print(barcode.pop()) 位于遍历 new_items 的 for 循环外部,此时 barcode 仅保留循环最后一次迭代的赋值结果。如果 new_items 最后一个 code 值未在 df 的 Code 列匹配到对应行,筛选得到的 row 是空 DataFrame,对应的 barcode 就是空列表,自然触发索引越界、空列表无法执行 pop() 的报错。
  2. 取值写法不严谨:df.loc[df['Code'] == code] 无论匹配到多少行,返回结果都是 DataFrame 类型,后续调用 .values.tolist() 可能得到空列表、单元素列表甚至多元素列表,不符合你预期的单值需求。

解决方案

直接优化取值逻辑,无需遍历列表:
使用 Pandas 内置的 .squeeze() 方法,可自动将单行单列的查询结果转为标量值,省去转列表、取索引的步骤:

for code in new_items:
    # 筛选后直接取对应列,用squeeze转标量
    barcode = df.loc[df['Code'] == code, 'Barcode'].squeeze()
    product_display_name = df.loc[df['Code'] == code, 'Product Display Name'].squeeze()
    # 其余字段同理,都可以用相同写法直接取到标量值
    
    # 此时可以直接使用barcode变量,无需处理列表
    print(barcode)

如果需要处理未匹配到条目的异常情况,可以加一层非空判断:

for code in new_items:
    match_row = df.loc[df['Code'] == code]
    if not match_row.empty:
        barcode = match_row['Barcode'].squeeze()
        product_display_name = match_row['Product Display Name'].squeeze()
        # 其余字段取值逻辑
    else:
        # 自定义未匹配到的处理逻辑,例如赋值为None、打日志等
        barcode = None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:36:03