由 Bruno0 解决。答案如下,评论中有其他修复。我留下了问题的描述,但将更正后的代码放在代码块中以供参考。我有一个用 NFL 球员的梦幻得分刮过的
框架。nfl_frame
该表按以下顺序排序:
- 周按升序排列
- 位置按此顺序 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 埃利奥特、泽克 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
Cats萌萌
相关分类