我正在使用df.iterrows()迭代資料框,但是當我嘗試將索引提取為變數時,它給了我這個錯誤raise KeyError(key) from err KeyError: '2022-09-15 09:00:00-04:00'
資料框
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
我的代碼
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
所以這條線導致了錯誤win_date = row[index]這很奇怪,因為在 KeyError 中它給了我正確的日期鏈接到該行但它導致了一個錯誤
uj5u.com熱心網友回復:
你可以試試這個,因為 index 已經是索引。行變數僅包含來自沒有索引的行的資訊。所以這樣做row[index]沒有意義。
你只想要日期正確嗎?所以設定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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512600.html
