Home > Mobile >  raise KeyError(key) from err while using iterrows
raise KeyError(key) from err while using iterrows

Time:10-11

I am using df.iterrows() to iterate a dataframe but when I try to extract the index as a variable it giving me this error raise KeyError(key) from err KeyError: '2022-09-15 09:00:00-04:00'

Dataframe

                                 Date       Open  ...        Low      Close
Datetime                                            ...                      
2022-01-05 11:00:00-05:00  18997.666667  78.269997  ...  78.070000  78.320000
2022-01-05 12:00:00-05:00  18997.708333  78.330002  ...  78.250000  78.410004
2022-01-05 13:00:00-05:00  18997.750000  78.400002  ...  78.269997  78.279999
2022-01-05 14:00:00-05:00  18997.791667  78.269997  ...  77.540001  77.620003
2022-01-05 15:00:00-05:00  18997.833333  77.620003  ...  77.010002  77.019997

my code

df = df.set_index(['Datetime'])
df = df.loc[reformated_date:]
print(df)

for index, row in df.iterrows():
    High = row['High']
    Low = row['Low']

    if type_trade == 'Sell':
        if Low <= TP:
            trade_result = 'Win'
            win_date = row[index]
            break

so it this line that cause the error win_date = row[index] It is weird because in the KeyError it give me the correct Date link to the row but it cause an Error

CodePudding user response:

You can try this instead, because index is already the index. The row variable only contains information from the row without the index. So doing row[index] doesn’t make sense.

You just want the date correct? So set win_date = index.

df = df.set_index(['Datetime'])
df = df.loc[reformated_date:]
print(df)

for index, row in df.iterrows():
    High = row['High']
    Low = row['Low']

    if type_trade == 'Sell':
        if Low <= TP:
            trade_result = 'Win'
            win_date = index
            break
  • Related