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

迭代DataFrame时出现KeyError: 'timeAccepted'的解决方法

解决DataFrame迭代时timeAccepted列的KeyError问题

我有一个包含timeAccepted列的DataFrame,尝试用以下代码迭代打印该列的值:

def print_time(df):
    print(df['timeAccepted'])
    for i, row in df.iterrows():
        print(df.columns)
        print(df.at[i, 'timeAccepted'])

运行时触发错误:

KeyError: 'timeAccepted'

但单独执行print(df['timeAccepted'])能正常输出该列数据:

0        2023-07-27T06:50:03.747135Z
1        2023-07-27T06:50:06.030559Z
2        2023-07-27T06:50:08.025268Z
3        2023-07-27T06:50:10.024531Z
4        2023-07-27T06:50:12.028957Z
                    ...             
26232    2023-07-27T12:46:27.024663Z
26233    2023-07-27T12:46:27.024663Z
26234    2023-07-27T12:45:02.027558Z
26235    2023-07-27T12:46:29.023594Z
26236    2023-07-27T12:46:29.023594Z
Name: timeAccepted, Length: 26237, dtype: object

执行print(df.columns)也能看到该列存在:

Index(['Order identification code', 'Initial quantity', 'side', 'Order type',
       'timeInForce', 'Limit price', 'quoteId', 'userId', 'timeAccepted'], dtype='object')

问题原因与解决办法

原因

iterrows()返回的i是DataFrame的原始索引值,而非连续的行号。如果你的DataFrame之前做过过滤、删除行等操作,索引可能出现不连续或非整数的情况,此时df.at[i, 'timeAccepted']会因为找不到对应的索引键触发KeyError。

解决办法

  1. 直接从迭代的row中取值(最推荐)
    既然已经通过iterrows()拿到了每行的row对象(Series类型),直接从row中提取列值即可,无需再通过DataFrame索引访问:

    def print_time(df):
        print(df['timeAccepted'])
        for i, row in df.iterrows():
            print(df.columns)
            print(row['timeAccepted'])  # 直接从row中获取
    
  2. 重置DataFrame索引
    如果一定要用df.at方法,可以先重置DataFrame的索引,确保索引是连续的整数:

    def print_time(df):
        df = df.reset_index(drop=True)  # 重置索引,丢弃旧索引
        print(df['timeAccepted'])
        for i, row in df.iterrows():
            print(df.columns)
            print(df.at[i, 'timeAccepted'])
    
  3. 改用iloc按位置访问
    若想按行的位置而非索引访问,可使用iloc,但需通过enumerate获取行的位置序号:

    def print_time(df):
        print(df['timeAccepted'])
        for idx, (i, row) in enumerate(df.iterrows()):
            print(df.columns)
            print(df.iloc[idx]['timeAccepted'])
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:25:26