首页 > 解决方案 > 累积计数,其中键等于 Python Pandas 中另一列的值

问题描述

我正在尝试为我的 DataFrame 中的每个团队编译累积计数,其中team = 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

我对熊猫很陌生,任何帮助将不胜感激。

标签: pythonpandascumsum

解决方案


Your second problem is a cumsum problem. You will need shift and cumsum inside a GroupBy.apply call.

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

推荐阅读