用dataframe.apply()替换for循环

时间:2019-06-15 14:55:15

标签: python python-3.x pandas

目标是将for循环替换为dataframe.apply()

下面是for循环的代码:

#ma is moving average of a number of days say 100
#days is the number of days for which stock data is available

 for d in range(ma-1, days):
     # Buy if stock price > Moving average & if not bought yet
     if df['Close'] > df['ma'] and cash == 1:
         buyPrice = closingprices[d + 1] #buy next day
         buy_data.append(buyPrice)
         cash = 0
         stock = 1

        if df['Close'] < df['ma'] and stock == 1:
            sellPrice = closingprices[d + 1]
            sell_data.append(sellPrice)
            cash = 1
            stock = 0

我无法找到正确的解决方案。

问题:我该如何设置拨动开关(现金指示器)并引用下一行元素?

df是完整的数据集,而buy_data是我想要的结果

buy_data = df.apply(lambda x : (x ['Close'+ 1]) if (x ['Close'] > x ['ma'] 
                    and cash ==1) else 0)

主要错误等

0 个答案:

没有答案