Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting in Multi-Layers – Pandas pivot_table

EXCEL PIVOT SORTING

I am looking for a solution to sort a pandas pivot table, as it is possible in Excel pivot tables, according to the aggregated values and thereby determine the order of the first level.
I have found a solution that uses pd.append.
A warning tells me that pd.append will not be available in the future and that I should therefore use pd.concat.

I have not managed to solve my problem with pd.concat.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is the solution with pd.append

>Solution :

You should use concat this way:

out = pd.concat([
      df_pivot.iloc[:-1]
              .assign(sort=lambda x: x['Totals'].groupby(level=0).transform('sum'))
              .sort_values(['sort','Name','Totals'], 
                           ascending=[False,True,False], kind='mergesort')
              .drop('sort', axis=1),
      df_pivot.iloc[[-1]] # slicing as DataFrame, not Series
           ])

Output:

Year            2019  2020  Totals
Name   A   B                      
Brian  foo one    20     0      20
       zz  xy     10     0      10
       bar two     0     9       9
           one     0     8       8
       zz  zz      0     5       5
Peter  foo one    20     0      20
       bar two     0     9       9
           one     6     0       6
Amy    foo two    11     0      11
           one     4     0       4
Totals            71    31     102
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading