Home » Python » Pandas Dataframe - Sort Multiple Column Values with Custom Key

Pandas Dataframe - Sort Multiple Column Values with Custom Key

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

Suppose you have the following data:

name price level reviews
Double Room with Private Bathroom 47 Exceptional 1
The Empire Brunei 309 Excellent 1464
Higher Hotel 24 Excellent 865
Radisson Hotel Brunei 120 Excellent 1314
Abdul Razak Hotel Apartment 59 Excellent 129

 

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:

name price level reviews
Double Room with Private Bathroom 47 Exceptional 1
The Empire Brunei 309 Excellent 1464
Radisson Hotel Brunei 120 Excellent 1314
Higher Hotel 24 Excellent 865
Abdul Razak Hotel Apartment 59 Excellent 129

 

See also: