为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白板的微信 2023-08-08 17:01:23
有人可以帮助解决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         Price2019-08-19   df.close_price[i=2019-08-19] # The closing price in data 2019-08-19xxxx-xx-xx   0xxxx-xx-xx   0xxxx-xx-xx   0xxxx-xx-xx   0xxxx-xx-xx   0xxxx-xx-xx   0xxxx-xx-xx   02019-08-27   df.close_i[i=2019-08-27] # The closing price in data 2019-08-27xxxx-xx-xx   0xxxx-xx-xx   0现在我想要:2019-08-19   df.close_price[i=2019-08-19] # The close in data 2019-08-19xxxx-xx-xx   df.close_price[i=2019-08-19] # The close in data 2019-08-19xxxx-xx-xx   df.close_price[i=2019-08-19] # The close in data 2019-08-19xxxx-xx-xx   df.close_price[i=2019-08-19] # The close in data 2019-08-19xxxx-xx-xx   df.close_price[i=2019-08-19] # The close in data 2019-08-19xxxx-xx-xx   df.close_price[i=2019-08-19] # The close in data 2019-08-19xxxx-xx-xx   df.close_price[i=2019-08-19] # The close in data 2019-08-19xxxx-xx-xx   df.close_price[i=2019-08-19] # The close in data 2019-08-192019-08-27   *df.close_price[i=2019-08-27]* # The close in data 2019-08-27xxxx-xx-xx   0xxxx-xx-xx   0我不是Python专家,我希望我说得足够清楚。预先感谢您,如果有人决定帮助我,我将非常感激。
查看完整描述

1 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

你可以使用一个变量,这里adding,既可以注意到你已经遇到了条件 1,记住你当时得到的值,也可以看到你还没有遇到条件 2,所以可以继续添加它:


adding = None


for i in range(1,len(close)):  

  if first_condition():  

    adding = close.close[i]

    list.append(adding) # 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 (close.fast_ema[i-1] > close.int_ema[i-1] and close.fast_ema[i] > close.slow_ema[i]:

    list.append(close.close)

    adding = None


  else: 

    if adding is not None:

      list.append(adding)

    else:

      list.append(0)


查看完整回答
反对 回复 2023-08-08
  • 1 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信