累积计数,其中键等于 Python Pandas 中另一列的值
Cumulative count where key equals value from another column in Python Pandas
我正在尝试为我的 DataFrame 中的每个 team 编译累积计数,其中 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
我是 pandas 的新手,我们将不胜感激。
你的第二个问题是 cumsum
问题。您将需要 shift
和 cumsum
在 GroupBy.apply
调用中。
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
我正在尝试为我的 DataFrame 中的每个 team 编译累积计数,其中 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
我是 pandas 的新手,我们将不胜感激。
你的第二个问题是 cumsum
问题。您将需要 shift
和 cumsum
在 GroupBy.apply
调用中。
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