0

I currently have a dataframe which include a column called timeAccepted.

I'm trying to print the value of timeAccepted for every iteration. I'm simply using the following code:

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

But I'm getting the following error:

KeyError: 'timeAccepted'

please note that print(df['timeAccepted']) have as an output:

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

and print(df.columns):

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

So, I've checked and the column do exist in the dataframe but I'm still having the KeyError! Please help!

Amani
  • 1
  • 1
    Unable to repro, but why not use `print(row['timeAccepted'])`? – BigBen Jul 27 '23 at 13:09
  • Please [edit] your post with a [reproducible example](https://stackoverflow.com/q/20109391/1422451) including sample data and full code from `import` lines to code that calls defined method. Test your reprex in an _empty_ Python environment preferably outside an IDE like the `python.exe` command line compiler. – Parfait Jul 27 '23 at 13:58
  • This solved the issue!! Thanks a lot for your help! – Amani Jul 27 '23 at 13:59

1 Answers1

1

Try to inspect the Index names a bit deeper:

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

I got a similar case where the index name had trailing whitespaces.

  • Thank you for you help. I've tried it and the strings are identical. Perhaps, the ```row['timeAccepted']``` solved the issue! – Amani Jul 27 '23 at 13:58