Python,For循环:如何在下一个单元格[i+1,i+2,.]中附加TRUE值[i],直到条件变为FALSE



有人能帮助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_prce。否则,代码会追加0。

A在这一点上,如果我假设交叉发生在数据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

我不是蟒蛇专家,我希望我已经足够清楚了。提前谢谢你,如果有人决定帮助我,我将非常感激。

您可以使用一个变量,此处为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)

最新更新