累计计数,其中键等于Python中另一列的值

2024-10-02 08:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的数据框中编译每个团队的累计计数,其中团队=df['result']=='W'。 “W”代表胜利,因此我试图计算在下一场比赛之前每队赢了多少场比赛。这是我的密码。你知道吗

df = pd.DataFrame({
'team': ['Inter', 'Barca', 'Psv', 'Totten', 'Psv', 'Barca', 'Inter', 'Totten', 'Totten', 'Psv', 'Inter', 'Barca'],
'result': ['W', 'W', 'L', 'L', 'D', 'W', 'D', 'W', 'W', 'L', 'D', 'D']
})

df['each_played'] = df.groupby('team').cumcount()
df['each_won'] = ???
print(df)

我已经成功地计算了每支球队在赛前打了多少场比赛,但无法让它为df['each_won']工作。你知道吗

期望输出:

     team       result       each_played    each_won
0    Inter      W            0              0
1    Barca      W            0              0
2      Psv      L            0              0
3   Totten      L            0              0
4      Psv      D            1              0
5    Barca      W            1              1
6    Inter      D            1              1
7   Totten      W            1              0
8   Totten      W            2              1
9      Psv      L            2              0
10   Inter      D            2              1
11   Barca      D            2              2

我对熊猫很陌生,任何帮助都将不胜感激。你知道吗


Tags: 数据密码df代表result团队team计数
1条回答
网友
1楼 · 发布于 2024-10-02 08:19:36

你的第二个问题是cumsum问题。在GroupBy.apply调用中需要shiftcumsum。你知道吗

df['each_won'] = (df.result
                    .eq('W')
                    .groupby(df.team)
                    .apply(lambda x: x.shift().cumsum())
                    .fillna(0, downcast='infer'))
df
      team result  each_played each_won
0    Inter      W            0        0
1    Barca      W            0        0
2      Psv      L            0        0
3   Totten      L            0        0
4      Psv      D            1        0
5    Barca      W            1        1
6    Inter      D            1        1
7   Totten      W            1        0
8   Totten      W            2        1
9      Psv      L            2        0
10   Inter      D            2        1
11   Barca      D            2        2

相关问题 更多 >

    热门问题