2

I've got the follow dataframe

import pandas as pd
df = pd.DataFrame({'Year': ['2012','2012','2012','2012','2012','2012','2012','2012','2012','2013', '2013','2013','2013','2013','2013','2013','2013','2013','2013'],
                   'Product':['X','X','X','Y','Z','W','X','X','X','Y','Z','W','Z','Z','W','Y','X','Z', 'Y'],   
                   'Country':['A','B','C','D','A','B','C','D','A','B','C','D','A','B','C','D','A','B', 'A'],                
                   'Units':[44,55,42,57,95,54,27,55,81,54,65,23,89,76,34,12,1,67,8],
                 })

# Pivot table to group by Country and Product
myPivot1 = pd.pivot_table(df,
                          values = ['Units'], index=['Country', 'Product'],
                          aggfunc=np.sum)
print(myPivot1)

and I'd like to sort the pivot table 'MyPivot1' in this way (sorted the 'Units' for each 'Country')

                 Units
Country Product       
A       Z          184
        X          126
        Y            8
B       Z          143
        X           55
        W           54
        Y           54
C       X           69
        Z           65
        W           34
D       Y           69
        X           55
        W           23
    

I tried this piece of code to sort 'Units':

myPivot2 = myPivot1.sort_values(('Units'), ascending=False)
print(myPivot2)

                 Units
Country Product       
A       Z          184
B       Z          143
A       X          126
C       X           69
D       Y           69
C       Z           65
B       X           55
D       X           55
B       W           54
        Y           54
C       W           34
D       W           23
A       Y            8

But, obviously, it sorts all the records, regardless if they are grouped by country.

1 Answer 1

3

I found the solution. Apart from sorting 'Units', I had to sort 'Country'.

myPivot2 = myPivot1.sort_values(by=['Country', 'Units'],
                                ascending=[True, False])


                Units
Country Product       
A       Z          184
        X          126
        Y            8
B       Z          143
        X           55
        W           54
        Y           54
C       X           69
        Z           65
        W           34
D       Y           69
        X           55
        W           23

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.