pandas 如何为迭代解决KeyError?

m1m5dgzv  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(129)

我目前有一个数据框架,其中包括一个名为timeAccepted的列。
我尝试打印每个迭代的timeAccepted的值。我只是使用以下代码:

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

字符串
但我得到了以下错误:

  1. KeyError: 'timeAccepted'


请注意print(df['timeAccepted'])作为输出:

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


print(df.columns)

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


所以,我已经检查了,数据框中确实存在列,但我仍然有KeyError!救命啊!

carvr3hs

carvr3hs1#

尝试更深入地检查索引名称:

  1. index_names = df.columns.to_list()
  2. time_accepted_index = index_names[-1]
  3. print(len(time_accepted_index))
  4. if not time_accepted_index == 'timeAccepted':
  5. print('strings are not the same')

字符串
我得到了一个类似的例子,其中索引名有尾随空格。

相关问题