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

求助:DataFrame中For循环未正确读取另一列值的问题

问题分析与解决:For循环无法正确获取DataFrame对应行的值

问题根源

你的代码里变量i从未更新,导致idx始终等于0,每次循环都在读取第0行的line 2值,而不是当前循环对应的行数据。这就是第3行满足条件却没添加-9的原因——程序判断时用的是第0行的line 2,而非第3行的。

修正方案

方案1:用enumerate直接获取索引(推荐)

enumerate可以同时拿到循环的索引和对应的值,避免手动维护索引出错:

open_line = []

for idx, line in enumerate(df["line 1"]):
    line2_val = df.iloc[idx]["line 2"]
    if 0 < line < 1000 and line2_val < 0:
        open_line.append(line2_val)
    elif line == 1000 and (line2_val == 1000 or 0 < line2_val < 1000):
        open_line.append("NAN")
    elif line < 0:
        open_line.append(line)

方案2:手动更新索引i

如果要保留原写法,需要在每次循环时递增i:

i = -1
open_line = []

for line in df["line 1"]:
    i += 1  # 关键:每次循环后更新i
    idx = i
    line2_val = df.iloc[idx]["line 2"]
    if (0 < line < 1000 and line2_val < 0):
        open_line.append(line2_val)
    elif line == 1000 and line2_val == 1000:
        open_line.append("NAN")
    elif line == 1000 and 0 < line2_val < 1000:
        open_line.append("NAN")
    elif line < 0:
        open_line.append(line)

额外优化

可以把两个判断line ==1000的分支合并,减少代码冗余,让逻辑更清晰(如方案1所示)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:12:26