由Bruno0解决。答案在下面,并在注释中进行了其他修复。我已经保留了问题的描述,但将更正后的代码放在了代码块中以供参考。
我有一个nfl_frame
帧,我抓取了NFL Player的幻想得分。该表的排序方式是:
-按升序排列
-按此顺序排列QB-> RB-> WR-> TE-> K->防御
-以降序排列的点
看起来像这样,但有更多的播放器和行:
周名称Fanduel_Points
1威尔逊,罗素31.78
1罗杰斯,亚伦30.76
1艾伦·乔希28.18
1拉马尔·杰克逊27.50
1默里·凯勒27.30
1卡马拉,阿尔文31.00
1艾略特(Zelke)30.00
2费城1.00
2杰克逊维尔0.00
2辛辛那提-2.00
2底特律-3.00
2达拉斯-3.00
我想做的是添加一个列有玩家位置的列。由于周和点的排序是一致的,因此我认为可以编写一个列表理解程序,以检查得分是否高于上一行,并沿着位置列表进行迭代以在出现标签时添加标签。然后,当连续的一周高于上一行时,我们将重新设置索引以从QB开始。代码如下:
##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
答案 0 :(得分:1)
角色用作“列表位置”的索引,但不受限制。
因此,如果在给定的一周内您有6条以上的行,并且总是以Fanduel_Price的价格增加,如此行中所述</ p>
elif df.Week[i] == df.Week[i-1] and df.Fanduel_Price[i] > df.Fanduel_Price[i-1]:
然后,角色的值达到6,您将获得该索引超出范围错误。
您可以如下限制角色的增加
Role=min(Role+1, len(Positions)-1)