简体   繁体   中英

Sort aggregated column in multiindex dataframe within groups

Taking inspiration from the data here we have the following Series/Dataframe

df = data.groupby(["Manufacturer","Product Name","Product Launch Data"]).sum("total")

                                                 total
Manufacturer Product Name Product Launch Date       
Apple        iPad         2010-04-03              30
             iPod         2001-10-23              34
Samsung      Galaxy       2009-04-27              24
             Galaxy Tab   2010-09-02              22

How do we sort after total while still keeping the groups ie ending up with:

                                                 total
Manufacturer Product Name Product Launch Date       
Apple        iPad         2010-04-03              30
             iPod         2001-10-23              34
Samsung      Galaxy Tab   2010-09-02              22
             Galaxy       2009-04-27              24

In last pandas versions is possible sorting by levels and columns names together, so here working:

df = df.sort_values(['Manufacturer','total'])
print (df)
                                               total
Manufacturer Product Name Product Launch Date       
Apple        iPad         2010-04-03              30
             iPod         2001-10-23              34
Samsung      Galaxy Tab   2010-09-02              22
             Galaxy       2009-04-27              24

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