Pandas 理解根据两个条件更改行值

Pandas Comprehension to Change Row value based on two conditions

由 Bruno0 解决。答案在下面,评论中有其他修复。我已经留下了问题的描述,但将更正后的代码放在代码块中以供参考。

我有一个框架nfl_frame 我已经用 NFL Player's fantasy Scores 抓取了。 Table 排序方式:

-周升序
-位置顺序QB->RB->WR->TE->K->Defense
-积分降序

它看起来像这样,但有更多的玩家和行数:

星期名称 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

角色用作列表位置的索引,但不受限制。

因此,如果在给定的一周内,您有超过 6 行且总是增加 Fanduel_Price,如该行所示

elif df.Week[i] == df.Week[i-1] and df.Fanduel_Price[i] > df.Fanduel_Price[i-1]:

然后 Role 的值达到 6,您会收到此索引超出范围的错误。

您可以按如下方式限制角色的增加

Role=min(Role+1, len(Positions)-1)