亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有重復名稱的數據框的 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 關注
  • 77 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號