How to Sort DataFrames in Pandas – From Basics to Real‑World Survey Data
Introduction
In this tutorial we explore the different ways to sort data using pandas. We start with a tiny DataFrame, then apply the same techniques to the large Stack Overflow Developer Survey dataset. By the end you will be able to:
- Sort by a single column (ascending or descending)
- Sort on multiple columns with independent sort directions
- Make the sort permanent with inplace=True
- Re‑order the index with sort_index
- Sort a single Series
- Quickly retrieve the largest or smallest values with nlargest / nsmallest
1. Sorting a Small DataFrame
df.sort_values(by='last') # ascending (default)
df.sort_values(by='last', ascending=False) # descending
The method returns a new DataFrame unless inplace=True is supplied.
2. Sorting on Multiple Columns
When the primary column contains duplicate values you can specify a secondary column:
# sort by last name (desc) then first name (desc)
df.sort_values(by=['last','first'], ascending=False)
If you need different sort directions per column, pass a list of booleans:
# last name descending, first name ascending
df.sort_values(by=['last','first'], ascending=[False, True])
3. Making the Sort Permanent
df.sort_values(by='last', ascending=False, inplace=True)
The original df is now reordered.
4. Restoring the Original Index Order
Use sort_index to reorder rows based on the index values:
df.sort_index(inplace=True)
5. Sorting a Single Column (Series)
A column can be treated as a Series and sorted directly:
df['last'].sort_values()
This returns a sorted Series without affecting the rest of the DataFrame.
6. Applying the Concepts to the Stack Overflow Survey Data
6.1 Sorting by Country
survey_df.sort_values('Country', inplace=True)
survey_df['Country'].head(50)
The first 50 rows now appear alphabetically (Afghanistan, Albania, …).
6.2 Sorting by Country and Salary
survey_df.sort_values(
by=['Country','ConvertedComp'],
ascending=[True, False],
inplace=True)
Countries stay alphabetical while salaries within each country are shown from highest to lowest. This quickly reveals outliers (e.g., a $2 million salary).
7. Getting the Largest / Smallest Values Efficiently
Instead of sorting the whole DataFrame, use nlargest or nsmallest:
# Top 10 salaries (Series)
survey_df['ConvertedComp'].nlargest(10)
# Top 10 rows with highest salaries (full DataFrame)
survey_df.nlargest(10, 'ConvertedComp')
# Smallest salaries
survey_df.nsmallest(10, 'ConvertedComp')
These methods return only the requested rows, saving time and memory.
8. Recap of Key Functions
DataFrame.sort_values()– sort by one or more columns.ascending– bool or list of bools to control direction per column.inplace=True– modify the original object.DataFrame.sort_index()– reorder by index.Series.sort_values()– sort a single column.DataFrame.nlargest()/DataFrame.nsmallest()– fetch extreme values.
9. What’s Next?
The next video will cover aggregating and grouping (e.g., median salary per country) to handle outliers and gain deeper insights.
Sponsor Mention
The tutorial is sponsored by Brilliant.org, a platform offering interactive lessons on data science, statistics, and Python. Use the link brilliant.org/forge/cms for a free trial and a 20 % discount on the annual premium plan.
Sorting in pandas is straightforward yet powerful: you can order data by any column, combine multiple sort keys with independent directions, make changes permanent, and instantly pull out the highest or lowest values. Mastering these techniques prepares you for more advanced analysis such as grouping, aggregation, and outlier handling.
Frequently Asked Questions
Who is Corey Schafer on YouTube?
Corey Schafer is a YouTube channel that publishes videos on a range of topics. Browse more summaries from this channel below.
Does this page include the full transcript of the video?
Yes, the full transcript for this video is available on this page. Click 'Show transcript' in the sidebar to read it.
9. What’s Next?
The next video will cover **aggregating and grouping** (e.g., median salary per country) to handle outliers and gain deeper insights.
Helpful resources related to this video
If you want to practice or explore the concepts discussed in the video, these commonly used tools may help.
Links may be affiliate links. We only include resources that are genuinely relevant to the topic.