You need to enable JavaScript to run this app. Python操作DataFrame时while循环出现'int'不可下标TypeError如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python操作DataFrame时while循环出现'int'不可下标TypeError如何解决

报错原因

你代码中初始化的row、row1都是整数类型的索引计数器,你直接对整数值执行row1['Qty']、row['left_qty']这类下标取值操作,但整数本身不支持通过[字段名]的方式取值,因此触发'int' object is not subscriptable报错。本质是混淆了「行索引数值」和「DataFrame行数据对象」两个概念,不能直接用索引值取对应行的字段。

同时原代码还存在两个隐藏问题:

  • 没有给row、row1添加自增逻辑,会导致循环卡死
  • row1没有在外层循环中重置,第一次外层循环跑完后row1等于Schedule_df的长度,后续外层循环的内层逻辑都不会执行
修复方案

方案1:保留while循环逻辑,通过索引定位DataFrame取值

修改后代码如下:

row = 0
while row < len(Exmil_df):
    # 每次进入外层循环时重置内层索引
    row1 = 0
    while row1 < len(Schedule_df):
        # 用loc通过索引+字段名取DataFrame对应值
        print(Schedule_df.loc[row1, 'Qty'])
        Schedule_df.loc[row1, 'Allocation'] = 0
        Exmil_df.loc[row, 'left_qty'] = Exmil_df.loc[row, 'Qty']
        # 内层索引自增
        row1 += 1
    # 外层索引自增
    row += 1

方案2:使用pandas原生行遍历语法,无需手动维护索引

更符合pandas使用习惯的写法如下,可读性更高:

# iterrows返回(行索引, 行数据对象)的元组
for idx, _ in Exmil_df.iterrows():
    for idx1, row1 in Schedule_df.iterrows():
        print(row1['Qty'])
        Schedule_df.loc[idx1, 'Allocation'] = 0
        Exmil_df.loc[idx, 'left_qty'] = Exmil_df.loc[idx, 'Qty']

如果你的业务场景是两个表的关联匹配,不建议使用嵌套循环,pandas提供的merge、向量化运算等方式性能会远高于循环遍历。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 07:45:03