Search code examples
pythonpandasmulti-index

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 i.e 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


Solution

  • 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