Promote one or more columns to be the data frame's index.
The index is not just row labels — it is what .loc selects by, what joins align on, and what makes time-based slicing possible. Choosing the right index is often the difference between a fiddly query and a one-liner.
Official documentation: DataFrame.set_index
The forms worth knowing
# One column becomes the index
df.set_index('time')
# Several columns become a MultiIndex
df.set_index(['Country', 'Status'])
# Keep the column as a column too, rather than consuming it
df.set_index('Country', drop=False)
# Undo it -- the index becomes an ordinary column again
df.reset_index()
set_index takes column names, not pd.col expressions, because it is asking which column rather than computing a value.
A worked example, on real data
The USGS publishes every earthquake it records as CSV, through a public API with no key — the source Bamboo Weekly #3 worked with.
Earthquakes are events in time, so the timestamp is the natural index. Once it is, you can slice by date range directly:
import pandas as pd
url = ('https://earthquake.usgs.gov/fdsnws/event/1/query.csv'
'?starttime=2024-01-01&endtime=2024-12-31&minmagnitude=6')
(
pd.read_csv(url, usecols=['time', 'place', 'mag'], parse_dates=['time'])
.set_index('time')
.sort_index()
.loc['2024-04-01':'2024-04-04']
)
Which gives:
place mag
time
2024-04-02 09:54:08.569000+00:00 137 km ENE of Saipan, Northern M... 6.2
2024-04-02 23:58:12.173000+00:00 15 km S of Hualien City, Taiwan 7.4
2024-04-03 00:11:25.266000+00:00 15 km NNE of Hualien City, Taiwan 6.4
2024-04-04 03:16:30.313000+00:00 77 km E of Minami-Sōma, Japan 6.1
That .loc['2024-04-01':'2024-04-04'] is the payoff. Because the index is a DatetimeIndex, Pandas understands partial date strings and slices by them — no comparison operators, no boolean mask. You could equally ask for .loc['2024-04'] to get the whole month.
The sort_index() matters: label-based slicing on an unsorted index raises an error or returns surprising results. Sort once, then slice freely.
Three mistakes people make
Slicing a DatetimeIndex that is not sorted. Range selection assumes monotonic order. If you get a KeyError on a date range that clearly exists, chain .sort_index() first.
Losing the column you indexed on. By default set_index moves the column into the index, so it is no longer available as a column. Pass drop=False if you need it in both places.
Setting an index that is not unique, then being surprised by .loc. A non-unique index is legal, but .loc['x'] then returns every matching row rather than one — a frame instead of a series. That is often what you want with a MultiIndex, and rarely what you want otherwise.
Watch it
Pandas time series superpowers: Why datetime indexes matter covers exactly the payoff above, and Load your data with the right index in Pandas shows how to set it at load time instead.
Practice it
Work through a set_index exercise, with instant feedback and no signup required: practice.lernerpython.com/bamboo-weekly/set-index/
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 106 Bamboo Weekly exercises that use set_index on real-world data — try each one, then study the worked solution.
- Bamboo Weekly #180: Movies
- Bamboo Weekly #178: Harmful algal bloom
- 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 #165: Artemis II
- Bamboo Weekly #164: Fertilizer
- Bamboo Weekly #163: Daylight saving time
- Bamboo Weekly #162: Spotify and car accidents
- Bamboo Weekly #160: Strait of Hormuz
- Bamboo Weekly #159: State of the Union
- Bamboo Weekly #157: Government corruption
- Bamboo Weekly #156: Winter Olympics
- Bamboo Weekly #155: Gold
- Bamboo Weekly #153: Venezuela
- Bamboo Weekly #152: Congestion pricing
- Bamboo Weekly #151: PyPI in 2025
- Bamboo Weekly #150: Kalshi
- Bamboo Weekly #149: Flu season
- Bamboo Weekly #147: Presidential pardons
- Bamboo Weekly #146: Thanksgiving travel
- Bamboo Weekly #144: Museum Heists
- Bamboo Weekly #143: Phones in school
- Bamboo Weekly #142: Hurricanes
- Bamboo Weekly #138: Federal workers
- Bamboo Weekly #137: UN Security Council
- Bamboo Weekly #135: Airline seats
- Bamboo Weekly #134: Taiwan weather
- Bamboo Weekly #133: Wind power
- Bamboo Weekly #131: Canadian border crossings
- Bamboo Weekly #129: Tom Lehrer
- Bamboo Weekly #128: Extreme heat
- Bamboo Weekly #124: NATO Spending
- Bamboo Weekly #123: Missiles
- Bamboo Weekly #122: Economic growth
- Bamboo Weekly #119: Python conferences
- Bamboo Weekly #114: International trade
- Bamboo Weekly #113: US airport traffic
- Bamboo Weekly #112: Programming jobs
- Bamboo Weekly #111: State taxes
- Bamboo Weekly #109: Cacao nibs
- Bamboo Weekly #108: Measles
- Bamboo Weekly #107: Consumer confidence
- Bamboo Weekly #106: Flu season
- Bamboo Weekly #104: Aviation accidents
- Bamboo Weekly #103: CDC data
- Bamboo Weekly #102: WordPress
- Bamboo Weekly #100: Sports betting
- Bamboo Weekly #96: Taylor Swift
- Bamboo Weekly #95: Tariffs
- Bamboo Weekly #93: Anti-politics
- Bamboo Weekly #91: Roller coasters
- Bamboo Weekly #89: Housing
- Bamboo Weekly #86: FEMA
- Bamboo Weekly #81: School
- Bamboo Weekly #78: Stock markets
- 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 #68: Dangerously hot weather
- Bamboo Weekly #65: Microplastics
- Bamboo Weekly #62: Economic report card
- Bamboo Weekly #61: Solar eclipse
- Bamboo Weekly #60: Iceland
- Bamboo Weekly #58: NATO
- Bamboo Weekly #56: Rent increases
- Bamboo Weekly #54: Household debt
- Bamboo Weekly #53: Airport animals
- Bamboo Weekly #52: Border encounters
- Bamboo Weekly #48: Aviation accidents
- Bamboo Weekly #45: Netflix
- Bamboo Weekly #44: Global economics
- Bamboo Weekly #43: Financial protection
- Bamboo Weekly #41: Wine production
- Bamboo Weekly #40: Sovereign Bonds
- Bamboo Weekly #36: Nobel Prize
- 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 #26: Hot weather
- Bamboo Weekly #25: Entrepreneurship
- Bamboo Weekly #24: Wildfire smoke
- Bamboo Weekly #23: Misery index
- Bamboo Weekly #21: Electric cars
- Bamboo Weekly #20: World inflation
- Bamboo Weekly #18: World population
- Bamboo Weekly #14: JOLTS
- Bamboo Weekly #12: Tourism
- Bamboo Weekly #9: US house prices
- Bamboo Weekly #8: Happiness
- Bamboo Weekly #6: End of the humanities?
- Bamboo Weekly #4: Eating well
- Bamboo Weekly #3: Earthquake
- Bamboo Weekly #1: Government corruption
Part of the Pandas Methods Index. See also practice by skill.