Pandas Dataframe - Sort Multiple Column Values with Custom Key

Pandas Dataframe - Sort Multiple Column Values with Custom Key

  • Python
  • 2 mins read

This Pandas Dataframe tutorial shows you how to sort multiple column values with a custom key.

Suppose you have the following data:

namepricelevelreviews
Double Room with Private Bathroom47Exceptional1
The Empire Brunei309Excellent1464
Higher Hotel24Excellent865
Radisson Hotel Brunei120Excellent1314
Abdul Razak Hotel Apartment59Excellent129

 

And you want to sort on the Level and Reviews column and you need to define the custom key for the level column. Below is an example:

ranking_level_sort = {
    "Exceptional": 5,
    "Excellent": 4,
    "Very good": 3,
    "Good": 2,
    "Review score": 1,
    "None": 0
}

Pandas Dataframe - Sort Mulitple Column Values with Custom Key Example

You can use the map for both columns, so in reviews no matching and returned NaN, so need to replace them with original values using fillna. Below is an example:

hotel_sorted = hotel.sort_values(by=["level", "reviews"],  
                                 key=lambda x: x.map(ranking_level_sort).fillna(x), 
                                 ascending=False)
hotel_sorted.reset_index(drop=True, inplace=True)

print (hotel_sorted)

Output:

namepricelevelreviews
Double Room with Private Bathroom47Exceptional1
The Empire Brunei309Excellent1464
Radisson Hotel Brunei120Excellent1314
Higher Hotel24Excellent865
Abdul Razak Hotel Apartment59Excellent129

 

See also: