0
0
Pandasdata~5 mins

sort_values() by multiple columns in Pandas

Choose your learning style9 modes available
Introduction

We use sort_values() to organize data in a table by one or more columns. This helps us see patterns or find specific information easily.

You want to list students by their grade and then by their name alphabetically.
You have sales data and want to sort first by date, then by amount.
You want to organize a list of products by category and then by price.
You need to prepare data for reports where order matters by multiple fields.
Syntax
Pandas
DataFrame.sort_values(by=[column1, column2, ...], ascending=[True, False, ...])

The by parameter takes a list of column names to sort by in order.

The ascending parameter takes a list of booleans to set ascending or descending order for each column.

Examples
Sorts the DataFrame first by age ascending, then by score ascending.
Pandas
df.sort_values(by=['age', 'score'])
Sorts by age ascending and score descending.
Pandas
df.sort_values(by=['age', 'score'], ascending=[True, False])
Sorts by city descending and name ascending.
Pandas
df.sort_values(by=['city', 'name'], ascending=[False, True])
Sample Program

This code creates a small table of people with their age and score. It sorts the table first by age from smallest to largest, then by score from largest to smallest within the same age.

Pandas
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
    'age': [25, 30, 25, 30, 22],
    'score': [85, 90, 85, 88, 95]
}
df = pd.DataFrame(data)

# Sort by age ascending, then score descending
sorted_df = df.sort_values(by=['age', 'score'], ascending=[True, False])
print(sorted_df)
OutputSuccess
Important Notes

If you do not provide ascending, all columns sort ascending by default.

Make sure the lists for by and ascending have the same length.

Sorting does not change the original DataFrame unless you use inplace=True.

Summary

sort_values() helps organize data by one or more columns.

You can control ascending or descending order for each column separately.

Sorting makes it easier to analyze and understand your data.