Home > Net >  single positional indexer is out-of-bounds.....for-loop problem
single positional indexer is out-of-bounds.....for-loop problem

Time:03-02

I have tried to run a for loop over a dataframe. Loop was running okay but while taking the output it's giving an error .. IndexError: single positional indexer is out-of-bounds

my code is as follows......

def ce_buy_sell(df):
    ce_buy = []
    ce_sell = []
    flag = -1
    for i in range(0, len(df)):
        precondition = (df['Low'].iloc[i 1] > df['Low'].iloc[i 2]) and (df['High'].iloc[i 1] < df['High'].iloc[i 2])
        if precondition == True and  df['High'].iloc[i] > df['High'].iloc[i 1]:
            ce_sell = ""
            if flag != 1:
                ce_buy = (df['Close'].iloc[i])
                flag = 1
            else:
               ce_sell = ""
        elif df['Low'].iloc[i] < df['Low'].iloc[i 1]:
            ce_buy =""
            if flag != 0:
                ce_sell = (df['Close'].iloc[i])
                flag = 0
            else:
                ce_buy = ""
        else:
            ce_buy =""
            ce_sell =""

    return(ce_buy, ce_sell)

a = ce_buy_sell(df)
df['CE Buy'] = a[0]
df['CE Sell'] = a[1]

Please give me some solution.

CodePudding user response:

you use "i 1" may be larger or equal len(df), which is out of bounds, you should c

CodePudding user response:

Obvious issue is that you run out of rows/cells. You use both i 1 and i 2 Without a check, so when you reach the final 2 for loop passes, the precondition throws an error that its out of range, because it is. Either change that precondition or add a check function that makes sure the index doesnt go out of bounds. How you implement this is up to you depending on what you do in the for loop itself.

  • Related