猿问

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

我正在尝试对包含多个相同名称的数据框执行累积和。我想创建另一个 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 Scored

0  John Smith      Duke   1-1-20            20

1  John Smith      Duke   1-3-20            30

2  John Smith      Duke   1-7-20            15

3  John Smith  Kentucky   1-3-20             8

4  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 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

在此先感谢您的帮助!


慕森卡
浏览 81回答 1
1回答

繁花不似锦

import numpy as npimport pandas as pddf = 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 heredf['Cumulative Sum Points Scored'] = df.groupby(['Player','School'])['Points Scored'].apply(np.cumsum)输出:   Player         School  Date         Points Scored      Cumulative Sum Points Scored0  John Smith      Duke   1-1-20             20                            201  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
随时随地看视频慕课网APP

相关分类

Python
我要回答