为了账号安全,请及时绑定邮箱和手机立即绑定

具有重复名称的数据框的 Groupby/cumsum

具有重复名称的数据框的 Groupby/cumsum

慕森卡 2022-07-26 17:09:30
我正在尝试对包含多个相同名称的数据框执行累积和。我想创建另一个 df,它具有每个玩家得分的累积总和,同时也认识到名称有时不是唯一的。学校将是第二个标准。这是我正在查看的示例:df = pd.DataFrame({'Player':['John Smith', 'John Smith', 'John Smith', 'John Smith', 'John Smith'],           'School':['Duke', 'Duke', 'Duke', 'Kentucky', 'Kentucky'],           'Date':['1-1-20', '1-3-20', '1-7-20', '1-3-20', '1-08-20'],           'Points Scored':['20', '30', '15', '8', '9']})print(df)     Player       School     Date    Points Scored0  John Smith      Duke   1-1-20            201  John Smith      Duke   1-3-20            302  John Smith      Duke   1-7-20            153  John Smith  Kentucky   1-3-20             84  John Smith  Kentucky  1-08-20             9我试过使用 df.groupby(by=['Player', 'School', 'Date']).sum().groupby(level=[0]).cumsum()... 但这并没有似乎区分了第二个标准。我也尝试按学校排序值,但在那里找不到任何运气。预期输出如下表所示;  Player        School              Date     Points Scored  Cumulative Sum Points Scored0  John Smith   Duke                  1-1-20          20              20                   1  John Smith   Duke                  1-3-20          30              502  John Smith   Duke                  1-7-20          15              653  John Smith   Kentucky              1-3-20           8              84  John Smith   Kentucky              1-08-20          9              17在此先感谢您的帮助!
查看完整描述

1 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

import numpy as np

import pandas as pd


df = pd.DataFrame({'Player':['John Smith', 'John Smith', 'John Smith', 'John     Smith', 'John Smith'],

       'School':['Duke', 'Duke', 'Duke', 'Kentucky', 'Kentucky'],

       'Date':['1-1-20', '1-3-20', '1-7-20', '1-3-20', '1-08-20'],

       'Points Scored':[20, 30, 15, 8, 9]}) # change to integer here


df['Cumulative Sum Points Scored'] = df.groupby(['Player','School'])['Points Scored'].apply(np.cumsum)

输出:


   Player         School  Date         Points Scored      Cumulative Sum Points Scored

0  John Smith      Duke   1-1-20             20                            20

1  John Smith      Duke   1-3-20             30                            50

2  John Smith      Duke   1-7-20             15                            65

3  John Smith  Kentucky   1-3-20              8                             8

4  John Smith  Kentucky  1-08-20              9                            17


查看完整回答
反对 回复 2022-07-26
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号