简体   繁体   中英

Rename Names of MultiIndex Pandas Dataframe

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:去向

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 !

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

df.columns = df.columns.map('_'.join)
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.

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