有人可以帮助解决Python中for循环语句的逻辑方案吗?我试图更清楚:我想构建一个 for 循环,如果一个条件为 TRUE,我想为下一个单元格附加相同的值,直到另一个条件变为 TRUE。
例如:我有一个名为 df 的数据框,有 3 列。第一列是股票的收盘价 (close_price),第二列包含快速指数移动平均线 (fast_ema),第三列包含慢速指数移动平均线 (ema_slow)。此时我运行以下代码:
list = []
for i in range(1,len(df)):
# FIRST CONDITION:
if (df.ema_fast[i-1] < df.ema_slow[i-1] and df.ema_fast[i] > df.ema_slow[i]:
list.append(df.close_price[i]) # i want to append close.close[i] for al the next cells i (i+1, i+2,...)
#until the SECOND condition become TRUE.
# SECOND CONDITION:
elif if (df.fast_ema[i-1] > df.ema_slow[i-1] and df.ema_fast[i] > df.ema_slow[i]:
list.append(df.close_price[i])
else:
list.append(0)
当短 EMA 与慢 EMA 交叉时,此代码会在列表中附加 close_price,然后,如果 ema_fast 向下交叉 ema_slow,则在发生交叉时,代码会附加 close_price。否则代码会追加 0。
此时,如果我假设交叉发生在数据 2019-08-19 中,交叉向下发生在数据 2019-08-27 中,我得到:
data Price
2019-08-19 df.close_price[i=2019-08-19] # The closing price in data 2019-08-19
xxxx-xx-xx 0
xxxx-xx-xx 0
xxxx-xx-xx 0
xxxx-xx-xx 0
xxxx-xx-xx 0
xxxx-xx-xx 0
xxxx-xx-xx 0
2019-08-27 df.close_i[i=2019-08-27] # The closing price in data 2019-08-27
xxxx-xx-xx 0
xxxx-xx-xx 0
现在我想要:
2019-08-19 df.close_price[i=2019-08-19] # The close in data 2019-08-19
xxxx-xx-xx df.close_price[i=2019-08-19] # The close in data 2019-08-19
xxxx-xx-xx df.close_price[i=2019-08-19] # The close in data 2019-08-19
xxxx-xx-xx df.close_price[i=2019-08-19] # The close in data 2019-08-19
xxxx-xx-xx df.close_price[i=2019-08-19] # The close in data 2019-08-19
xxxx-xx-xx df.close_price[i=2019-08-19] # The close in data 2019-08-19
xxxx-xx-xx df.close_price[i=2019-08-19] # The close in data 2019-08-19
xxxx-xx-xx df.close_price[i=2019-08-19] # The close in data 2019-08-19
2019-08-27 *df.close_price[i=2019-08-27]* # The close in data 2019-08-27
xxxx-xx-xx 0
xxxx-xx-xx 0
我不是Python专家,我希望我说得足够清楚。预先感谢您,如果有人决定帮助我,我将非常感激。
皈依舞
相关分类