简体   繁体   中英

Pandas groupby sum resulting in blanks

I have a pandas dataframe which looks like this:

Sub Code Date End Date Monthly Sub Budget Monthly Sub Spend Cum Sub Spend
345 3450 9-1-20 12-1-20 $100 $70
345 3450 10-1-20 12-1-20 $100 $50
345 3450 11-1-20 12-1-20 $100 $80
345 3450 12-1-20 12-1-20 $100 $50
345 3451 12-1-21 1-1-21 $90 $10
981 9810 11-1-20 1-1-21 $80 $50
981 9810 12-1-20 1-1-21 $80 $30

I want to calculate both 'Total Subscription Budget' (the sum of all monthly subscription budgets) and 'Cumulative Subscription Budget' (cumulative sum of monthly subscription budgets) so that the df would look like this:

Sub Code Date End Date Monthly Sub Budget Monthly Sub Spend Cum Sub Spend Tot Sub Budget Cum Sub Budget
3450 9-1-20 12-1-20 $100 $70 $70 $400 $100
3450 10-1-20 12-1-20 $100 $50 $120 $400 $200
3450 11-1-20 12-1-20 $100 $80 $200 $400 $300
3450 12-1-20 12-1-20 $100 $50 $250 $400 $400
3451 12-1-21 1-1-21 $90 $10 $10 $90 $100
9810 11-1-20 1-1-21 $80 $50 $50 $160 $80
9810 12-1-20 1-1-21 $80 $30 $80 $160 $160

Right now I am using the below code which is working for the cumsum but not for the sum. The Cumulative Sub Budget column is populated correctly, but the Total Sub Budget column is empty.

df['Total Subscription Budget'] = df.groupby('Sub Code')['Monthly Sub Budget'].sum()  
df['Cumulative Subscription Budget'] = df.groupby('Sub Code')['Monthly Sub Budget'].cumsum()

I have found plenty of cases where sum worked and cumsum didn't but haven't seen anyone else have this problem. What should I do to make the .sum() work?

Try with transform

df['Total Subscription Budget'] = df.groupby('Sub Code')['Monthly Sub Budget'].transform('sum')  

Here is a roundabout approach:

#Sum does not work because it doesn't repeat the value for each row.
x = df.groupby('Sub Code')['Monthly Sub Budget'].sum()
x.rename('Total Subscription Budget', inplace=True)
#I think what we can do is join this output to the main table like this
pd.merge(df, x, on='Sub Code')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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