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

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

在 pandas 數據透視表中運行總和(python)

在 pandas 數據透視表中運行總和(python)

慕哥6287543 2023-07-27 16:20:30
我有一個如下所示的數據框:df = pd.DataFrame({'publisher': ['facebook', 'facebook', 'facebook', 'google', 'google', 'google'],          'month_leadgen': ['2019-01', '2019-01', '2019-01', '2019-02', '2019-02', '2019-03'],         'month_payment': ['2019-01', '2019-02', '2019-03', '2019-02', '2019-03', '2019-03'],         'revenue': [60, 25, 45, 85, 90, 60]})我創建了一個數據透視表:df = df.pivot_table(index=['publisher', 'month_leadgen'], columns=['month_payment'], values=['revenue']).reset_index()    publisher   month_leadgen   revenuemonth_payment            2019-01  2019-02  2019-030   facebook    2019-01  60.0     25.0     45.01   google      2019-02  NaN      85.0     90.02   google      2019-03  NaN      NaN      60.0我的預期輸出是按月匯總總和。因此,對于 facebook,我希望在 2019-02 列(第 1 個月 + 第 2 個月)中看到 85.0。Facebook 的 2019-03 欄將為 125.0(第 1 個月 + 第 2 個月 + 第 3 個月)。謝謝。
查看完整描述

2 回答

?
料青山看我應如是

TA貢獻1772條經驗 獲得超8個贊

讓我們試試.cumsum()axis=1。那就是cumsum(1)。


df=df.join(df[['revenue']].cumsum(1).rename(columns=dict(revenue='Cumsum')))




publisher month_leadgen                     revenue                  Cumsum          \

month_payment                         2019-01 2019-02 2019-03   2019-01 2019-02   

0              facebook       2019-01    60.0    25.0    45.0    60.0    85.0   

1                google       2019-02     NaN    85.0    90.0     NaN    85.0   

2                google       2019-03     NaN     NaN    60.0     NaN     NaN   


                       

month_payment 2019-03  

0               130.0  

1               175.0  

2                60.0  

或者,在樞軸階段進行;

df2 = df=df.pivot_table(index=['month_leadgen','publisher'], columns=['month_payment'], values=['revenue']).cumsum(axis=1).reset_index()



查看完整回答
反對 回復 2023-07-27
?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

只需以這種方式定義您的數據集,并將發布者作為索引:

df = pd.DataFrame( { 'month_leadgen': ['2019-01', '2019-01', '2019-01', '2019-02', '2019-02', '2019-03'], '月付款': ['2019-01', '2019-02', '2019-03', '2019-02', '2019-03', '2019-03'], '收入': [60, 25, 45, 85, 90, 60] }, 索引 = ['facebook', 'facebook', 'facebook', 'google', 'google', 'google'] )

然后執行執行這一行:

df['TotalShifted'] = df.groupby(level=0)['收入'].transform(lambda x: x.cumsum().shift(0))

您將獲得:

Month_leadgen Month_ payment 收入 TotalShifted facebook 2019-01 2019-01 60 60 facebook 2019-01 2019-02 25 85 facebook 2019-01 2019-03 45 130 google 2019-02 2019-02 85 85 google 2019-02 201 9-03 90 175 谷歌2019年3月 2019年3月 60 235


http://img1.sycdn.imooc.com//64c229250001b1c806540522.jpg

查看完整回答
反對 回復 2023-07-27
  • 2 回答
  • 0 關注
  • 192 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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