Q.Can you sort a DataFrame with respect to multiple columns?
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Yes, you can sort a DataFrame by multiple columns using the sort_values() method with a list of column names, and you can specify ascending/descending order for each column individually.
The Core Idea: Multi-Column Sorting
When you sort a DataFrame by multiple columns, you're telling pandas: "First, arrange all rows by Column A. Then, for rows that have the same value in Column A, arrange those tied rows by Column B." This is exactly like sorting a spreadsheet by one column, then by another within the ties.
The tool for this is DataFrame.sort_values(). The key insight is that the by parameter accepts a list of column names, and the ascending parameter accepts either a single boolean (applied to all columns) or a list of booleans (one per column).
How It Works
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({
'Department': ['Sales', 'Sales', 'IT', 'IT', 'HR'],
'Employee': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
'Salary': [50000, 60000, 70000, 55000, 65000]
})
# Sort by Department (ascending), then by Salary (descending)
sorted_df = df.sort_values(by=['Department', 'Salary'], ascending=[True, False])
print(sorted_df)
Expected Output:
| Department | Employee | Salary |
|---|---|---|
| HR | Eve | 65000 |
| IT | Charlie | 70000 |
| IT | Diana | 55000 |
| Sales | Bob | 60000 |
| Sales | Alice | 50000 |
Notice what happened:
- First, all rows are grouped by Department in alphabetical order (HR, IT, Sales).
- Within each Department group, rows are sorted by Salary from highest to lowest (because
Falsemeans descending). - In the IT department, Charlie (70000) comes before Diana (55000).
The Syntax Breakdown
df.sort_values(by=['col1', 'col2'], ascending=[True, False])
by: A list of column names. The order matters — the first column is the primary sort key, the second is the secondary key, and so on.ascending: A list of booleans.Truemeans ascending (A→Z, low→high),Falsemeans descending (Z→A, high→low). The list must be the same length asby.
If you want the same order for all columns, you can pass a single boolean: ascending=True sorts all columns ascending, ascending=False sorts all descending.
Common Pitfall …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.