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

使用set_index和resample后遍历Pandas DataFrame出现KeyError:0问题

解决重采样后遍历DataFrame出现KeyError:0的问题

问题原因

用set_index+resample处理后,DataFrame的索引已经变成时间戳类型,不再是默认的整数序列(0、1、2...)。你原来的df[i,"value"]是按索引标签取值,但整数i并不是时间索引里的标签,自然找不到对应行,触发KeyError:0。重采样前能用是因为那时的索引是默认整数,刚好和循环的i匹配。

正确的遍历方法

1. 用iloc按位置访问

iloc专门按整数位置定位,不管索引是什么类型都生效:

for i in range(len(df)):
    print(df.iloc[i]["value"])

2. 直接遍历行(推荐)

用pandas自带的行遍历方法,比手动写range更高效:

  • 用iterrows()获取每行的索引和数据:
for idx, row in df.iterrows():
    print(row["value"])
  • 用itertuples()返回命名元组,访问速度更快:
for row in df.itertuples():
    print(row.value)

3. 直接遍历目标列

如果只需要"value"列的数据,直接遍历列最简洁:

for val in df["value"]:
    print(val)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:45:32