Loading content...
Loading content...
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.
Sorting is not just cosmeticβit is a core analytical tool used to answer executive questions:
sort_values()The primary method is df.sort_values(). By default, it sorts in ascending order:
Sort the product sales catalog below:
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:
Sort the employee table below across multiple hierarchies:
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.
In data pipelines, filter first to isolate the relevant records, then chain .sort_values():
na_position)Missing values (NaN) require positioning rules. Pandas defaults to placing them at the bottom:
df.sort_index()While sort_values() orders by column data, sort_index() restores or orders by the DataFrame index:
Complete the 4 organizational ranking tasks:
Test your understanding of sort_values, sort directions, tie-breaking, and index sorting:
Test your understanding with real-world query prediction and syntax questions.
What is the default sorting order when executing df.sort_values("Sales")?