Sort rows by the values in one or more columns.
sort_values is the method that turns a correct answer into a readable one. A grouped total sorted alphabetically tells you almost nothing; the same total sorted descending tells you who the biggest players are at a glance.
Official documentation: DataFrame.sort_values
The forms worth knowing
# One column, largest first
df.sort_values('Capacity (MW)', ascending=False)
# Several columns -- earlier ones win ties
df.sort_values(['Country', 'Capacity (MW)'])
# A different direction per column
df.sort_values(['Country', 'Capacity (MW)'], ascending=[True, False])
# Missing values first instead of last
df.sort_values('mag', na_position='first')
# Sort a Series (e.g. the result of groupby or value_counts)
df.groupby('Country')['Capacity (MW)'].sum().sort_values(ascending=False)
Note that sort_values takes column names as strings, not pd.col expressions — it wants to know which column, not a computed value.
A worked example, on real data
The Global Coal Plant Tracker lists every coal-fired generating unit on earth, one row per unit. Bamboo Weekly #64 used this dataset.
Suppose we want each country's units listed together, biggest first within each country. That is a two-key sort with different directions:
import pandas as pd
url = ('https://www.bambooweekly.com/content/files/wp-content/uploads/2024/02/'
'global-coal-plant-tracker-january-2024.xlsx')
(
pd.read_excel(url, sheet_name='Units',
usecols=['Country', 'Status', 'Capacity (MW)'])
.sort_values(['Country', 'Capacity (MW)'], ascending=[True, False])
.head(4)
)
Which gives:
Country Capacity (MW) Status
Albania 800.0 cancelled
Argentina 375.0 operating
Argentina 120.0 operating
Argentina 120.0 construction
Countries ascending, capacity descending inside each — the ascending=[True, False] list is what makes those two directions possible in a single call.
Three mistakes people make
Forgetting that it returns a new frame. df.sort_values('x') does not reorder df; it hands back a sorted copy. Either chain onto it or keep the result. (inplace=True exists but works against method chaining, and its behavior changed in Pandas 3 — prefer the returned value.)
Sorting a grouped result and losing the sort. groupby returns results ordered by the group key. If you sort and then group, the grouping re-sorts by key and your work is gone. Sort after aggregating, not before.
Assuming the index comes along in a useful order. After sorting, the index is shuffled — row 0 is no longer the first row of the original. If positional access matters afterwards, chain .reset_index(drop=True).
Watch it
How to sort in Pandas covers this in a few minutes.
Practice it
Work through a sort_values exercise, with instant feedback and no signup required: practice.lernerpython.com/bamboo-weekly/sort-values/
Go deeper
Bamboo Weekly is the practice. If you want the structured version — full courses with downloadable Jupyter notebooks, plus live Pandas office hours when you get stuck — that is LernerPython+Data. A paid Bamboo Weekly subscription is included with it.
See it on real data
Below are the 108 Bamboo Weekly exercises that use sort_values on real-world data — try each one, then study the worked solution.
- Bamboo Weekly #181: Housing costs
- Bamboo Weekly #180: Movies
- Bamboo Weekly #179: Krakow tourism
- Bamboo Weekly #177: European Summer
- Bamboo Weekly #176: Religious restrictions
- Bamboo Weekly #175: Inflation
- Bamboo Weekly #174: Vacation
- Bamboo Weekly #173: IPOs
- Bamboo Weekly #172: World Cup
- Bamboo Weekly #170: Port of Long Beach
- Bamboo Weekly #169: Press freedom
- Bamboo Weekly #168: US gas prices
- Bamboo Weekly #166: Income tax
- Bamboo Weekly #164: Fertilizer
- Bamboo Weekly #161: Missiles in Israel
- Bamboo Weekly #159: State of the Union
- Bamboo Weekly #158: University endowments
- Bamboo Weekly #157: Government corruption
- Bamboo Weekly #156: Winter Olympics
- Bamboo Weekly #155: Gold
- Bamboo Weekly #154: University rankings
- Bamboo Weekly #153: Venezuela
- Bamboo Weekly #152: Congestion pricing
- Bamboo Weekly #150: Kalshi
- Bamboo Weekly #149: Flu season
- Bamboo Weekly #148: US Manufacturing
- Bamboo Weekly #144: Museum Heists
- Bamboo Weekly #142: Hurricanes
- Bamboo Weekly #138: Federal workers
- Bamboo Weekly #137: UN Security Council
- Bamboo Weekly #136: Indian vehicles
- Bamboo Weekly #132: JetBrains survey
- Bamboo Weekly #126: EV sales
- Bamboo Weekly #125: Shrinking dollars
- Bamboo Weekly #124: NATO Spending
- Bamboo Weekly #119: Python conferences
- Bamboo Weekly #118: Flight delays
- Bamboo Weekly #117: Electricity
- Bamboo Weekly #114: International trade
- Bamboo Weekly #113: US airport traffic
- Bamboo Weekly #111: State taxes
- Bamboo Weekly #100: Sports betting
- Bamboo Weekly #99: Literacy and numeracy
- Bamboo Weekly #98: Retail sales
- Bamboo Weekly #97: Drones
- Bamboo Weekly #96: Taylor Swift
- Bamboo Weekly #93: Anti-politics
- Bamboo Weekly #92: Climate disaster costs
- Bamboo Weekly #91: Roller coasters
- Bamboo Weekly #90: Voter participation
- Bamboo Weekly #87: Nuclear power
- Bamboo Weekly #83: Gasoline prices
- Bamboo Weekly #82: Broadband
- Bamboo Weekly #81: School
- Bamboo Weekly #79: Cyber attacks
- Bamboo Weekly #77: Paris Olympics
- Bamboo Weekly #76: Aging legislators
- Bamboo Weekly #73: Avocado hand
- Bamboo Weekly #72: City travel
- Bamboo Weekly #71: Holidays
- Bamboo Weekly #70: Moon missions
- Bamboo Weekly #69: Election participation
- Bamboo Weekly #68: Dangerously hot weather
- Bamboo Weekly #65: Microplastics
- Bamboo Weekly #64: Coal power
- Bamboo Weekly #63: Ukraine aid
- Bamboo Weekly #62: Economic report card
- Bamboo Weekly #61: Solar eclipse
- Bamboo Weekly #60: Iceland
- Bamboo Weekly #58: NATO
- Bamboo Weekly #54: Household debt
- Bamboo Weekly #52: Border encounters
- Bamboo Weekly #51: Academy Awards
- Bamboo Weekly #49: Campaign finance
- Bamboo Weekly #48: Aviation accidents
- Bamboo Weekly #47: Minimum wage
- Bamboo Weekly #45: Netflix
- Bamboo Weekly #44: Global economics
- Bamboo Weekly #41: Wine production
- Bamboo Weekly #35: Terrorism
- Bamboo Weekly #34: House of Representatives
- Bamboo Weekly #33: Fracking
- Bamboo Weekly #32: Unions
- Bamboo Weekly #31: Poverty
- Bamboo Weekly #30: Uncertainty
- Bamboo Weekly #29: Auto accidents
- Bamboo Weekly #28: Pret a Manger
- Bamboo Weekly #27: Young voters
- Bamboo Weekly #26: Hot weather
- Bamboo Weekly #25: Entrepreneurship
- Bamboo Weekly #24: Wildfire smoke
- Bamboo Weekly #23: Misery index
- Bamboo Weekly #22: Banana index
- Bamboo Weekly #21: Electric cars
- Bamboo Weekly #18: World population
- Bamboo Weekly #16: Consumer oil prices
- Bamboo Weekly #15: Eurovision
- Bamboo Weekly #14: JOLTS
- Bamboo Weekly #13: Python developers
- Bamboo Weekly #12: Tourism
- Bamboo Weekly #11: Software jobs
- Bamboo Weekly #9: US house prices
- Bamboo Weekly #8: Happiness
- Bamboo Weekly #7: Bank failures
- Bamboo Weekly #6: End of the humanities?
- Bamboo Weekly #5: Ukrainian exports
- Bamboo Weekly #4: Eating well
- Bamboo Weekly #1: Government corruption
Part of the Pandas Methods Index. See also practice by skill.