熊猫单个位置索引器超出范围

时间:2019-10-07 08:34:28

标签: python pandas dataframe

我查看了以前有关该主题的帖子,但没有帮助

def trendFinder():
    uptrend = pd.DataFrame()
    counts = 0
    x = 0
    for i in range(len(df)):
        trendSlot = pd.DataFrame
        trendSlot = (df.loc[x+1:x+10])
        closeAvg = (sum(trendSlot[:]['Close'])/10)
        openAvg = (sum(trendSlot[:]['Open'])/10)
        if trendSlot.iloc[-1]['Close'] > closeAvg:
            print('close average: ',closeAvg)
            print('open average:  ',openAvg)
            print(trendSlot)
            sleep(0.1)
            clear_output()
            counts +=1
        x+=10
    print(counts)

这里基本上发生的是,在每次迭代中,都会创建一个具有原始df的行/列的小型数据帧。那么对于小型数据框,如果最后一行的收盘价大于所有收盘价的平均值,则将打印该小型数据框。该函数会平稳运行一段时间(我认为直到最后一次迭代),直到发生某些事情会产生此错误:

---> 12         if trendSlot.iloc[-1]['Close'] > closeAvg:
...
IndexError: single positional indexer is out-of-bounds

1 个答案:

答案 0 :(得分:1)

如果您向if语句添加条件,例如:

if (len(trendSlot) > 0) and (trendSlot.iloc[-1]['Close'] > closeAvg):

应该避免尝试失败的trendSlot.iloc[-1],以防其为空。