Pandas — Sorting Data
Transform raw tables into ranked analytical views. Master single and multi-column ordering withsort_values(), configure ascending/descending directions, understand tie-breaking hierarchies, chain filtering with sorting, and manage missing values with na_position.
1. Why Sort Data in Analytics?
Sorting is not just cosmetic—it is a core analytical tool used to answer executive questions:
2. Sorting by One Column: sort_values()
The primary method is df.sort_values(). By default, it sorts in ascending order:
df_asc = df.sort_values("Sales")
# 2. Descending order (highest to lowest / Z-A)
df_desc = df.sort_values("Sales", ascending=False)
3. 🔥 Live Single-Column Sorting Lab
Sort the product sales catalog below:
4. Sorting by Multiple Columns & Tie-Breaking
When sorting by multiple columns, pass a list of column names. Pandas sorts by the first column first, then uses subsequent columns to break ties:
df.sort_values(
["Department", "Salary"],
ascending=[True, False]
)
5. 🔥 Live Multi-Column Sorting Lab
Sort the employee table below across multiple hierarchies:
6. Sorting vs. Filtering
Beginners often conflate sorting and filtering. Keep this mental model clear:
"Show me products with Sales > 50000."
Rows that fail the condition are excluded from the resulting DataFrame.
"Show me products ordered from highest to lowest."
All rows remain present; only their relative position is rearranged.
7. 🔥 Combining Filtering and Sorting
In data pipelines, filter first to isolate the relevant records, then chain .sort_values():
8. Sorting with Missing Values (na_position)
Missing values (NaN) require positioning rules. Pandas defaults to placing them at the bottom:
df.sort_values("Sales", na_position="last")
# 2. na_position="first" (NaN values appear at the very top)
df.sort_values("Sales", na_position="first")
9. Sorting by Index: df.sort_index()
While sort_values() orders by column data, sort_index() restores or orders by the DataFrame index:
df.sort_index()
# Sort by index descending
df.sort_index(ascending=False)
11. 🔥 Final Live Challenge: Employee Analytics
Complete the 4 organizational ranking tasks:
- Sort employees by Performance from highest to lowest
- Sort employees by Salary from lowest to highest
- Sort by Department (ascending) and Performance (descending)
- Filter Performance >= 80, then sort by Salary descending
12. Knowledge Assessment Quiz
Test your understanding of sort_values, sort directions, tie-breaking, and index sorting:
Pandas Sorting Certification Quiz
Test your understanding with real-world query prediction and syntax questions.
What is the default sorting order when executing df.sort_values("Sales")?