简体   繁体   English

重命名 MultiIndex 的名称 Pandas Dataframe

[英]Rename Names of MultiIndex Pandas Dataframe

I'm in trouble with a dataframe created from a groupby function.我遇到了从 function 组创建的groupby的麻烦。

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但我想将id_prodprice重命名为no_salesrevenue但我不知道该怎么做,因为 MultiIndex

with the print(df.columns) the result is:使用print(df.columns)结果是:

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 !所以是这个names=[]我想改 谢谢你的帮助!

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. level=0表示在多索引中可以找到要重命名的键的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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