如何进入Pandas`iterrows()`的下一个索引?

时间:2017-11-05 02:42:24

标签: python pandas dataframe iterator valueerror

假设我有一个类似的数据框:

              JPM
2008-01-02  38.47
2008-01-03  38.20
2008-01-04  39.33

编辑:预期输出:

            Symbol Order   Shares
2011-01-10  JPM    NOTHING 0
2011-01-13  JPM    BUY     1000
2011-01-13  JPM    SELL    0

如何将第二行与第一行进行比较?我想看看SPY的值是否在第二天比第一天更高。

现在我有以下代码:

for index, row in df_prices.iterrows():
     if df_prices[index + 1]['Symbol'] > df_prices[index]['Symbol'] and curr_hold == 0:
         df_orders[index]['Order'] = 'Sell'
         df_orders[index]['Shares'] += 1000

但是我收到了错误:

ValueError: Cannot add integral value to Timestamp without freq.

我认为这是因为我做index + 1。因此,我不知道如何在我的应用程序中使用iterrows()

编辑:在评论者的建议之后,这是我的新代码,上面有预期的输出。

if df_prices['JPM'].shift(1) > df_prices['JPM'] and curr_hold == 0:
    df_orders['Order'] = 'Sell'
    df_orders['Shares'] += 1000
elif df_prices['JPM'].shift(1) < df_prices['JPM'] and curr_hold == 0:
    df_orders['Order'] = 'Buy'
    df_orders['Shares'] -= 1000
elif df_prices['JPM'].shift(1) > df_prices['JPM'] and curr_hold == -1000:
    df_orders['Order'] = 'Hold'
elif df_prices['JPM'].shift(1) < df_prices['JPM'] and curr_hold == 1000:
    df_orders['Order'] = 'Hold'

1 个答案:

答案 0 :(得分:1)

对于最初询问的索引转换问题,您需要使用shift

i

为了更清楚,这里是移位列的样子,

df['SPY'].shift(1) > df['SPY'] 
# in place of df_prices[index + 1]['SPY'] > df_prices[index]['SPY']