SOLVED by Bruno0. answer is below, with additional fixes in comments. I have left the description of the problem, but placed the corrected code in the code block for reference.
I have a frame nfl_frame
I've scraped with NFL Player's fantasy Scores. The Table is sorted by:
-Week in ascending order
-Position in this order QB->RB->WR->TE->K->Defense
-Points in descending order
It looks like this, but with many more players and rows:
Week Name Fanduel_Points
1 Wilson, Russell 31.78
1 Rodgers, Aaron 30.76
1 Allen, Josh 28.18
1 Jackson, Lamar 27.50
1 Murray, Kyler 27.30
1 Kamara, Alvin 31.00
1 Elliot, Zeke 30.00
2 Philadelphia 1.00
2 Jacksonville 0.00
2 Cincinnati -2.00
2 Detroit -3.00
2 Dallas -3.00
What I'd like to do is add a column with the player's position. Since the week and points sorting is consistent, I figured I could write a list comprehension that would check for if the points scored was higher than the previous row, and iterate along a list of positions to add the label when that occurred. Then, when the week for a row was higher than the previous row, we'd reset the index to start from QB again. the code looks like this:
##writing comprehension to perform task listed above
#creating empty list that I will add each position to
Result = ['QB']
#list of positions
Positions = list(['QB','RB','WR','TE','Def'])
def add_position(df):
#creating list of my positions
#setting index as 0 to start with QB
Role = 0
#loop checking for week number and points scored
for i in range(1,len(df)):
#if week for new row matches week for last row, and points for new row <= last row, then same position as last row
if df.Week[i]== df.Week[i-1] and df.Fanduel_Points[i]<= df.Fanduel_Points[i-1]:
Result.append(Positions[Role])
#if week for new row matches week for last row, and points for new row > last row, then next position in list
elif df.Week[i] == df.Week[i-1] and df.Fanduel_Points[i] > df.Fanduel_Points[i-1]:
Role +=1
Result.append(Positions[Role])
#if new week, reset and begin from Positions[0] to begin labeling as QB again
elif df.Week[i] > df.Week[i-1] :
Role = 0
Result.append(Positions[Role])
#running my comprehension on the frame
add_position(nfl_frame)
#apply add_position to my position column
nfl_frame['Position'] = Result
Role is used as an index for List Position, but is unbounded.
Thus if in a given week you have more than 6 lines with always increasing Fanduel_Price, as expressed in this line
Then Role with reach a value of 6 and you get this index out of range error.
You could limit the increasing of Role as follows