Sorting DataFrame by Multiple Columns

Write a Pandas program to sort the DataFrame first by ‘name’ in descending order, then by ‘score’ in ascending order.

Example 1:

Input: DataFrame with 'name' and 'score' columns 
Output: Sorted DataFrame

Example 2:

Input: DataFrame with 'name' and 'score' columns 
Output: Sorted DataFrame

Use pandas DataFrame sort_values() function to sort DataFrame by multiple columns.

import pandas as pd

def sort_df(df):
    return df.sort_values(['name', 'score'], ascending=[False, True])

df1 = pd.DataFrame({'name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'score': [85, 90, 87, 91]})
df2 = pd.DataFrame({'name': ['Adam', 'Eve', 'Stark', 'Rogers'], 'score': [88, 92, 95, 97]})

print(sort_df(df1))
print(sort_df(df2))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!