jbachlombardo
jbachlombardo

Reputation: 141

Sorting within pandas groupby (multi-index)

EDIT: To put in sample data df and expected output. EDIT 2: I've modified the data slightly so that the results are not uniformly largest number associated with 'cc' in each case.

My problem is:

The df is:

df = pd.DataFrame({'Index1': ['A', 'A', 'A', 'B', 'B', 'B'],
                'Index2': ['aa', 'bb', 'cc', 'aa', 'bb', 'cc'],
                'X': [1, 2, 7, 3, 6, 1],
                'Y': [2, 3, 6, 2, 4, 1],
                'Z': [3, 5, 9, 1, 2, 1]})

Then the code is:

df_scored = pd.DataFrame()   #new df to hold results
cats = [X, Y, Z]             #categories (columns of df) to be scaled
grouped = df.groupby([Index 1, Index 2]).sum()
for cat in cats :
    df_scored[cat] = grouped.groupby(level = 0)[cat].apply(lambda x: x / x.max())
df_scored['Score'] = df_scored.sum(axis = 1)

This produces:

                      X         Y         Z     Score
Index1 Index2                                        
A      aa      0.142857  0.333333  0.333333  0.809524
       bb      0.285714  0.500000  0.555556  1.341270
       cc      1.000000  1.000000  1.000000  3.000000
B      aa      0.500000  0.500000  0.500000  1.500000
       bb      1.000000  1.000000  1.000000  3.000000
       cc      0.166667  0.250000  0.500000  0.916667

Now I want to sort the resulting df_scored by each grouping of Index 1 (so that Index 2 is sorted by 'Score' within each group of Index 1), with this as the desired result:

                      X         Y         Z     Score
Index1 Index2                                        
A      cc      1.000000  1.000000  1.000000  3.000000
       bb      0.285714  0.500000  0.555556  1.341270
       aa      0.142857  0.333333  0.333333  0.809524
B      bb      1.000000  1.000000  1.000000  3.000000
       aa      0.500000  0.500000  0.500000  1.500000
       cc      0.166667  0.250000  0.500000  0.916667

How do I do this?

I've seen a few other questions on this here and here but not getting it to work for me in this case.

Upvotes: 4

Views: 4266

Answers (1)

Sociopath
Sociopath

Reputation: 13401

Add this at the end of your code

df_scored.sort_values('Score', ascending= False).sort_index(level='Index1', sort_remaining=False)

Upvotes: 6

Related Questions