[英]Pandas groupby cumulative sum ignore current row
我知道關於這個主題有一些問題(比如Pandas: Cumulative sum of one column based on value of another )但是,它們都不能完全滿足我的要求。
假設我有一個像這樣的數據框
我想按月計算 Cost 分組的累積總和,避免考慮當前值,以獲得 Desired 列。通過使用groupby
和cumsum
我獲得 colum CumSum
生成數據幀的 DDL 是
df = pd.DataFrame({'Month': [1,1,1,2,2,1,3],
'Cost': [5,8,10,1,3,4,1]})
IIUC 你可以使用groupby.cumsum
然后減去cost
;
df['cumsum_'] = df.groupby('Month').Cost.cumsum().sub(df.Cost)
print(df)
Month Cost cumsum_
0 1 5 0
1 1 8 5
2 1 10 13
3 2 1 0
4 2 3 1
5 1 4 23
6 3 1 0
您可以執行以下操作:
df['agg']=df.groupby('Month')['Cost'].shift().fillna(0)
df['Cumsum']=df['Cost']+df['agg']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.