Search code examples
dataframesortingalphabetical

How to sort 2 columns in a Dataframe, one sorted in descending order and the other in alphabetical order corresponding to the 1st column


Dataframes looks something like

Names            Rank
Michael            8
David              6
Christopher        6
Brian              5
Amanda             3
Heather            8
Sarah              2
Rebecca            4

Expected O/P

Names         Rank
Heather        8
Michael        8
Christopher    6
David          6
Brian          5
Rebecca        4
Amanda         3
Sarah          2

Here, I need to first sort the rank column in descending order and then the Name column in alphabetical order.

My code :

df = df.sort_values(['Name'],ascending = True)
df = df.'Name'.sort_values(['Rank'],ascending = False)
df

This code gives me on the sorted rank but the Name column doesn't get sorted.


Solution

  • df = df.sort_values(['Rank', 'Name'],ascending = [False, True])