Sorting by Column Values
Sort a DataFrame by one or more columns with sort_values(), control ascending/descending order, and handle NaN placement.
Sorting by Column Values is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Sorting Matters
Sorting a DataFrame is important for presentation (top-N reports, leaderboards), correctness (time series operations require chronological order), and performance (binary search on a sorted index is O(log n) vs O(n)). Pandas' sort_values() method is the primary tool for sorting by column content, and it returns a new DataFrame without modifying the original.
import pandas as pd
df = pd.DataFrame({
'name': ['Dave', 'Alice', 'Carol', 'Bob'],
'score': [75, 92, 88, 65]
})
# Sort by score descending (highest first)
ranked = df.sort_values('score', ascending=False)
print(ranked)
# name score
# 1 Alice 92
# 2 Carol 88
# 0 Dave 75
# 3 Bob 65sort_values() — Basic Usage
DataFrame.sort_values(by) sorts rows by the values in the specified column. The by argument accepts a single column name (string) or a list of column names for multi-key sorting. By default, sorting is ascending (smallest first). Pass ascending=False for descending order.
import pandas as pd
df = pd.DataFrame({
'product': ['B', 'A', 'C', 'A', 'B'],
'price': [20, 10, 30, 15, 25]
})
# Ascending by price (default)
print(df.sort_values('price'))
# product price
# 1 A 10
# 3 A 15
# 0 B 20
# 4 B 25
# 2 C 30Sorting by Multiple Columns
Passing a list of column names to sort_values(by=) sorts by the first column, then breaks ties using the second column, and so on. The ascending parameter can also be a list of booleans matching the order of the columns, allowing different sort directions for each key.
import pandas as pd
df = pd.DataFrame({
'dept': ['HR', 'Eng', 'HR', 'Eng', 'Sales'],
'salary': [50000, 90000, 60000, 80000, 70000],
'name': ['Alice', 'Bob', 'Carol', 'Dave', 'Eve']
})
# Sort by dept A-Z, then by salary descending within each dept
sorted_df = df.sort_values(
by=['dept', 'salary'],
ascending=[True, False]
)
print(sorted_df)
# dept salary name
# 1 Eng 90000 Bob
# 3 Eng 80000 Dave
# 2 HR 60000 Carol
# 0 HR 50000 Alice
# 4 Sales 70000 EveNaN Placement with na_position
By default, NaN values are sorted to the end of the result regardless of ascending or descending order. Use the na_position parameter to control this: 'last' (default) or 'first'. Deciding where NaN appears matters in ranked tables — missing values might represent 'unknown' and should be clearly separated from valid ranked entries.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Carol', 'Dave'],
'score': [92, np.nan, 88, np.nan]
})
# NaN last (default)
print(df.sort_values('score', ascending=False, na_position='last'))
# name score
# 0 Alice 92.0
# 2 Carol 88.0
# 1 Bob NaN
# 3 Dave NaN
# NaN first
print(df.sort_values('score', na_position='first').head(2))Stable Sort and kind= Parameter
Pandas uses a stable sort by default (mergesort, which is O(n log n)) — when two rows have equal values in the sort key, their original relative order is preserved. This stability matters when you sort by a primary key first, then by a secondary key: the primary sort order is maintained among ties of the secondary sort. You can change the algorithm with kind='quicksort' (faster but unstable) or kind='heapsort'.
import pandas as pd
df = pd.DataFrame({
'group': ['A', 'B', 'A', 'B'],
'value': [10, 10, 20, 20],
'original_row': [0, 1, 2, 3]
})
# Stable sort: equal values keep original relative order
result = df.sort_values('value', kind='mergesort')
print(result)
# group value original_row
# 0 A 10 0
# 1 B 10 1 <- row 0 before row 1 (stable)
# 2 A 20 2
# 3 B 20 3inplace=True vs Reassignment
Like most Pandas methods, sort_values() returns a new DataFrame by default. Passing inplace=True modifies the DataFrame in place and returns None. Using inplace is generally discouraged in modern Pandas because it makes code harder to pipeline and debug — it is easier to always reassign: df = df.sort_values('col').
import pandas as pd
df = pd.DataFrame({'x': [3, 1, 4, 1, 5]})
# Preferred: reassign
df = df.sort_values('x')
print(df['x'].tolist()) # [1, 1, 3, 4, 5]
# Alternative: inplace (not recommended for pipelines)
df2 = pd.DataFrame({'x': [3, 1, 4]})
df2.sort_values('x', inplace=True)
print(df2['x'].tolist()) # [1, 3, 4]Resetting the Index After Sorting
After sorting, the row index reflects the original positions. In a table sorted descending, row 0 might now have index 4. Call .reset_index(drop=True) to reassign sequential indices starting from 0. This is important before using .iloc[0] to get the first-ranked row reliably, or before exporting to a file where index gaps look confusing.
import pandas as pd
df = pd.DataFrame({'score': [70, 90, 80]})
sorted_df = df.sort_values('score', ascending=False)
print(sorted_df)
# score
# 1 90
# 2 80
# 0 70
# Clean sequential index
reset_df = sorted_df.reset_index(drop=True)
print(reset_df)
# score
# 0 90
# 1 80
# 2 70Getting Top-N with nlargest() and nsmallest()
For selecting the top-N or bottom-N rows by a column value, df.nlargest(n, 'col') and df.nsmallest(n, 'col') are more efficient than sorting the entire DataFrame and slicing. They use a partial sort (heap selection) that is O(n log k) rather than O(n log n), which matters for large DataFrames.
import pandas as pd
df = pd.DataFrame({
'product': ['A', 'B', 'C', 'D', 'E'],
'revenue': [5000, 12000, 8000, 3000, 15000]
})
# Top 3 by revenue
top3 = df.nlargest(3, 'revenue')
print(top3)
# product revenue
# 4 E 15000
# 1 B 12000
# 2 C 8000
# Bottom 2 by revenue
bottom2 = df.nsmallest(2, 'revenue')
print(bottom2)Sorting Categorical Columns by Category Order
When sorting a column that contains an ordered Categorical dtype, sort_values() respects the category order rather than alphabetical order. This is essential for correctly ordering priority levels, severity ratings, or size labels — 'Small' should come before 'Medium' before 'Large', not in alphabetical order where 'Large' comes first.
import pandas as pd
df = pd.DataFrame({
'size': pd.Categorical(
['Large', 'Small', 'Medium', 'Small', 'Large'],
categories=['Small', 'Medium', 'Large'],
ordered=True
),
'count': [10, 5, 8, 3, 7]
})
print(df.sort_values('size'))
# size count
# 1 Small 5
# 3 Small 3
# 2 Medium 8
# 0 Large 10
# 4 Large 7Chaining Sort with Other Operations
Because sort_values() returns a DataFrame, it integrates naturally into method chains. A typical pattern is: filter rows → aggregate → sort → display top-N. Chaining keeps the transformation pipeline linear and readable.
import pandas as pd
df = pd.DataFrame({
'dept': ['Eng', 'HR', 'Eng', 'Sales', 'HR', 'Eng'],
'salary': [90000, 50000, 120000, 70000, 55000, 80000]
})
result = (
df
.groupby('dept')['salary'].mean()
.reset_index()
.sort_values('salary', ascending=False)
.head(2)
)
print(result)
# dept salary
# 0 Eng 96666.67
# 2 Sales 70000.00Practical: Top-5 Products Report
Here is a practical end-to-end example of producing a top-5 products report by revenue: load data, compute total revenue per product, sort descending, take the top 5, reset the index to produce a clean rank number, and add a rank column for display.
import pandas as pd
orders = pd.DataFrame({
'product': ['A', 'B', 'A', 'C', 'B', 'D', 'E', 'A', 'C', 'E'],
'revenue': [100, 200, 150, 80, 300, 60, 400, 120, 90, 350]
})
top5 = (
orders
.groupby('product')['revenue'].sum()
.reset_index()
.sort_values('revenue', ascending=False)
.head(5)
.reset_index(drop=True)
)
top5.index = top5.index + 1 # rank from 1
top5.index.name = 'rank'
print(top5)Quick Check
Test your understanding of sorting DataFrames by column values.
Lesson Recap
In this lesson you learned: sort_values(by=) sorts by one or more columns, ascending= can be a list for different directions per key, na_position='last' controls NaN placement, and nlargest()/nsmallest() efficiently extract the top/bottom N rows without sorting the entire DataFrame. Always reset_index() after sorting for clean sequential output. Next up we sort by the DataFrame index.
Frequently asked questions
Is the “Sorting by Column Values” lesson free?
Yes — the full text of “Sorting by Column Values” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “Sorting by Column Values”?
Sort a DataFrame by one or more columns with sort_values(), control ascending/descending order, and handle NaN placement. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Sorting by Column Values” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Sorting by Column Values
- Sorting by Index
- Ranking Values
- Setting and Resetting the Index