猿问

Python,For 循环:如何将 TRUE 值 [i] 追加到下一个单元格

有人可以帮助解决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专家,我希望我说得足够清楚。预先感谢您,如果有人决定帮助我,我将非常感激。


白板的微信
浏览 105回答 1
1回答

皈依舞

你可以使用一个变量,这里adding,既可以注意到你已经遇到了条件 1,记住你当时得到的值,也可以看到你还没有遇到条件 2,所以可以继续添加它:adding = Nonefor i in range(1,len(close)):&nbsp;&nbsp;&nbsp; if first_condition():&nbsp;&nbsp;&nbsp; &nbsp; adding = close.close[i]&nbsp; &nbsp; list.append(adding) # i want to append close.close[i] for al the next cells i (i+1, i+2,...)&nbsp; #until the SECOND condition become TRUE.&nbsp; &nbsp;&nbsp; # SECOND CONDITION:&nbsp; elif if (close.fast_ema[i-1] > close.int_ema[i-1] and close.fast_ema[i] > close.slow_ema[i]:&nbsp; &nbsp; list.append(close.close)&nbsp; &nbsp; adding = None&nbsp; else:&nbsp;&nbsp; &nbsp; if adding is not None:&nbsp; &nbsp; &nbsp; list.append(adding)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; list.append(0)
随时随地看视频慕课网APP

相关分类

Python
我要回答