5

I'm in trouble with a dataframe created from a groupby function.

df = base.groupby(['year', 'categ']).agg({'id_prod':'count', 'price':'sum'}).unstack(level=1)

it returns this result : df

but I would like to rename id_prod and price to no_sales and revenue but I don't know how to do that because of the MultiIndex

with the print(df.columns) the result is :

MultiIndex([('id_prod', 0),
            ('id_prod', 1),
            ('id_prod', 2),
            (  'price', 0),
            (  'price', 1),
            (  'price', 2)],
           names=[None, 'categ'])

So is this names=[] I would like to change Thanks for your help !

benson23
  • 16,369
  • 9
  • 19
  • 38
Lilly_Co
  • 169
  • 12

2 Answers2

4

Short and simple , it would just rename your columns with respect to Multi-index

df.columns = df.columns.map('_'.join)
suraj
  • 81
  • 4
2
df = df.rename(columns={'id_prod': 'no_sales', 'price': 'revenue'}, level=0)

The level=0 indicates where in the multi-index the keys to be renamed can be found.

BrsG
  • 146
  • 3