python - 累积计数,其中键等于 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
我对熊猫很陌生,任何帮助将不胜感激。
解决方案
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
推荐阅读
- c# - 使用 MemoryStream 读取 excel 文件
- python - 如何使用python在列表/数组中搜索字母?
- reactjs - 无法为 Redux-Form 设置 initialValues
- javascript - 用Javascript打印字母
- ios - iOS 13 如何将 UIDocumentPickerViewController 与 App Group 一起使用?
- android - 为什么我必须分开
在 google play 上显示“打开”按钮? - c++ - 指向类类型数组和带有 new 的构造函数的指针
- android - 我可以从通知中启动对话活动,使其显示在我的应用程序窗口上而不是空白背景上吗?
- android - 为什么当适配器调用notifyDataSetChanged时recyclerview不可见,消失或消失?
- r - 将多个列名复制到每行的变量中