Rename the multiple column when .groupby.agg(['sum'])

Question:

How to rename the multiple column when .groupby.agg(['sum'])?

dk = new_df1.groupby(['Product','Date'])['Sale1', 'Sale2'].agg(['sum']).reset_index().rename(columns={'sum':'First_Sale', 'Second_Sale'})

It will show First_Sale, sum for the Sale1 column and Second_Sale, sum for the Sale2 column.

Anyone can assist?

Asked By: beginofwork

||

Answers:

This should work: Note that I removed [] around 'sum' and added them around the column names 'Sale1', 'Sale2':

rename = {'Sale1': 'First_Sale', 'Sale2': 'Second_Sale'}

dk = new_df1.groupby(['Product', 'Date'])[['Sale1', 'Sale2']].agg('sum').reset_index().rename(columns=rename)
Answered By: T C Molenaar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.