Maverick
Maverick

Reputation: 799

Unexpected pandas index error when using a for loop

I have a Pandas DataFrame with the shape - (133, 6) - and I am trying to use iloc to iterate down the frame then select and append chunks of data to a list.

I have a list of start positions:

start_positions = [6, 32, 58, 84, 110]

and the end positions are +7 rows, so I have tried this:

frames = []
for x in start_positions:
    frames.append(df.iloc[start_positions[x] : start_positions[x]+7])

However is throwing:

IndexError: index 6 is out of bounds for axis 0 with size 5

Which I don’t quite understand as this works if I manually increment through start_positions.

Upvotes: 0

Views: 475

Answers (3)

Vishakha Lall
Vishakha Lall

Reputation: 1314

Another possible solution would be to use:

frames = []
for x in start_positions:
    frames.append(df.iloc[x:x+7])

x is an element of start_positions and can be accessed as is, had it been an index it would be used the way you did.

Upvotes: 0

nucsit026
nucsit026

Reputation: 720

Try to use for x in range(len(start_positions)) instead of for x in start_positions as:

frames = []
for x in range(len(start_positions)):
    print(start_positions[x],":",start_positions[x]+7)

It results:

6 : 13
32 : 39
58 : 65
84 : 91
110 : 117

Upvotes: 1

eddys
eddys

Reputation: 1187

The code has problem right from the start in the for loop I think. Look at start_positions[x] in frames.append(df.iloc[start_positions[x] : start_positions[x]+7]). The value of x in the for loop starts from 6 but the maximum index start_positionscan have is 4 since len(start_positions)=5

@Maverick , I think what you may want to do is remove start_positions and have something like this (but didnt test the code)

for x in start_positions:
    frames.append(df.iloc[x : x+7])

Upvotes: 1

Related Questions