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.
sort_values() by multiple columns in 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.
age ascending, then by score ascending.df.sort_values(by=['age', 'score'])
age ascending and score descending.df.sort_values(by=['age', 'score'], ascending=[True, False])
city descending and name ascending.df.sort_values(by=['city', 'name'], ascending=[False, True])
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.
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)
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.
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.