python - 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_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 专家,我希望我足够清楚。在此先感谢您,如果有人决定帮助我,我将不胜感激。
解决方案
你可以在这里使用一个变量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)
推荐阅读
- python - 我应该如何编写一个返回多个值的递归函数?
- api-platform.com - 为 API 平台中的自定义操作禁用 requestBody
- python - Python中有效的numpy数组计算
- java - 图不支持事务
- sql-server - SSDT:错误:Deploy72002:标识符必须至少包含一个名称(例如,MyTable)。完成构建项目“Common.sqlproj”——失败
- html - 如何延迟动画,直到用户加载元素
- android - 安卓的 tflite 模型加密
- minecraft - 在我对启动画面进行编码后,我的世界崩溃了
- python - 如何清除 Python3 正则表达式中指定的标志?
- r - 箱线图按月