我正在尝试遍历数据帧行并根据条件将新列设置为 1 或 0。直到 if 语句工作正常,但是一旦添加了 elif 部分,它就会给我一个“索引越界错误”。关于如何解决这个问题的任何想法?
low=history.low
high = history.high
history['bottom'] = " "
history['top']=" "
for i in range(len(history)):
if (low[i] < low[i-1]) and (low[i] < low[i-2]) and (low[i] < low[i+1]) and (low[i] < low[i+2]) :
history['bottom'][i] = 1
elif (high[i] > high[i-1]) and (high[i] > high[i-2]) and (high[i] > high[i+1]) and (high[i] > high[i+2]):
history['top'][i]=1
else:
history['top'][i] = 0
history['bottom'][i] = 0
答案 0 :(得分:0)
@Code-Apprentice 解释了我们的一个错误
其他我发现的,我认为你正在寻找的就是排队的
history['bottom'][i] = 1
和 history['top'][i]=1
您正在尝试更改可能不存在的索引的值。
例如,如果 i = 1
则上面指定的行将产生错误,因为它们中不存在索引 1。 (它们只有索引 0)。
您可以使用 .append
添加值而不是使用索引来更改值
答案 1 :(得分:0)
这是因为它试图访问一个不存在的索引。我想查看上面的更多代码,以了解 history.low
和 history.high
所指的值。
但是你在错误之前得到任何结果了吗?
另外,请解释len(history)
。在您的代码中有一个历史字典,其中有 history['bottom'] = " "
和 history['top']=" "
,但同时您有 low=history.low
和 high = history.high
。这两个历史对象/变量有什么区别?
请展示更多您的代码。