亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號