Sub topic 13
Using set_index for lookups
This chapter assumes you can build a DataFrame from a dictionary, select columns with brackets, and use .loc with labels. If .loc slicing is unfamiliar, review it first.
Why turn a column into the index
The index is the set of row labels. When a column holds a unique identifier, such as a city name, you can move it into the index. Then .loc finds a row by that identifier, with no boolean mask.
set_index does this. It returns a new DataFrame and leaves the original unchanged.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"country": ["Norway", "Peru", "India", "Egypt", "Ecuador"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)
by_city = df.set_index("city")
print(by_city)
print(by_city.loc["Lima"])
print(by_city.loc["Lima", "population_k"])The city column is now the index, so it no longer appears among the columns. by_city.loc["Lima"] returns the whole row as a Series. by_city.loc["Lima", "population_k"] returns one value.
Comparing the two approaches
You can get the same answer with a mask on the original frame. The index version is shorter, and it states the intent: look up this key.
print(df.loc[df["city"] == "Lima", "population_k"])
print(by_city.loc["Lima", "population_k"])These two lines differ in what they return. The mask version returns a Series, because a mask can match zero, one, or many rows. The index version returns a single value, because a label is expected to identify one row. This holds only if the labels are unique.
Looking up several keys
Pass a list of labels to .loc to get several rows at once. The rows come back in the order you list them.
print(by_city.loc[["Quito", "Oslo"]])
print(by_city.loc[["Quito", "Oslo"], "population_k"])A list of labels returns a DataFrame (or a Series if you also name one column). A missing label in the list raises a KeyError, so check membership first when the keys come from outside your data.
wanted = ["Quito", "Oslo", "Paris"]
present = [name for name in wanted if name in by_city.index]
print(by_city.loc[present])Common errors
Duplicate labels are the main trap. .loc does not require a unique index. If two rows share a label, .loc returns all of them as a DataFrame, and code that expects a single value then breaks. Check uniqueness before you rely on the index as a key.
print(by_city.index.is_unique)Other points to keep in mind:
set_index("city")removes the column. Usedf.set_index("city", drop=False)to keep a copy of it as a regular column.- The old index (
atoe) is discarded. Callreset_index()later to turn the labels back into a column. - Labels are case-sensitive.
"lima"does not match"Lima".
Summary
Use set_index when a column identifies each row and you will look rows up by that identifier. Check index.is_unique first, and remember that .loc with a single label returns a Series or scalar only when the label appears once.
Exercise
Using by_city, write one expression that returns the continent of Pune as a single value. Then explain what you would see if the index held "Pune" twice.
Show answer
by_city.loc["Pune", "continent"] returns "Asia". If "Pune" appeared twice, the same expression would return a Series with two entries instead of one value, because .loc returns every row that matches the label.