繁体   English   中英

Pandas 中的累计和

[英]Cumulative Sum in Pandas

我有一个 dataframe,它看起来像这样:

project_code   start_date   end_date   date       spend
     489        5/15/18     5/15/19     3/1/19     100
     489        5/15/18     5/15/19     4/1/19     250
     489        5/15/18     5/15/19     5/1/19     50
     511        4/1/19      4/1/20      2/1/20     90
     511        4/1/19      4/1/20      3/1/20     50       
     489        5/15/19     5/15/20     3/1/20     100

我需要在同一个表中创建另一列来计算该订阅期的累计支出(由开始和结束日期定义)。 因此,它应该在项目代码下添加所有以前的支出,只要它们具有相同的开始/结束日期。

project_code   start_date   end_date   date       spend    cumulative_subscription_spend
     489        5/15/18     5/15/19     3/1/19     100           100
     489        5/15/18     5/15/19     4/1/19     250           350
     489        5/15/18     5/15/19     5/1/19     50            400
     511        4/1/19      4/1/20      2/1/20     90            90
     511        4/1/19      4/1/20      3/1/20     50            140
     489        6/1/19      6/1/20      3/1/20     100           100

我见过的关于这个问题的大多数版本都使用 groupby/aggregate,但我无法弄清楚它如何作为同一个表中的新列工作。

检查groupby + cumsum

df['cumulative_subscription_spend'] = df.groupby('project_code')['spend'].cumsum()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM