Sub topic 13
Using set_index for lookups
This chapter shows how to turn a column into the row index so you can look up rows by a meaningful key. It assumes you know how .loc and .iloc work, how boolean masks filter rows, and what a DataFrame's index, columns, and values are.
Why make a column the index
A default DataFrame is labeled 0, 1, 2, .... Those numbers carry no meaning, so finding the row for Lima means writing a mask such as df["city"] == "Lima". If you look rows up by city often, you can make city the index instead. Then .loc["Lima"] finds the row directly.
DataFrame.set_index does this. It returns a new DataFrame, so the original is unchanged unless you assign the result back.
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.index)
print(by_city.columns)The city column is now the index, and it no longer appears in columns. The old labels a to e are discarded. The remaining columns are country, population_k, and continent.
Looking up with .loc
Once the index holds the key, .loc accepts the key directly.
print(by_city.loc["Lima"])
print(by_city.loc["Lima", "population_k"])
print(by_city.loc[["Quito", "Oslo"], ["country", "population_k"]])The three calls return different shapes:
by_city.loc["Lima"]returns a Series. Its index is the column names and its values are Lima's row.by_city.loc["Lima", "population_k"]returns one value.- A list of labels returns a DataFrame, with rows in the order you asked for, not the order in the table. Here Quito comes before Oslo.
You can also pull one column out as a Series and index into it. Its index is the cities, so this works like a dictionary lookup.
pop = by_city["population_k"]
print(pop["Cairo"])
print(pop[["Cairo", "Pune"]])The two routes return different types. A mask always returns a DataFrame, even for one match. A unique label in .loc returns a Series. If you need a DataFrame, pass a list: by_city.loc[["Lima"]].
Missing keys
A label that is not in the index raises KeyError. This can be a good thing, because a typo fails loudly instead of returning an empty result.
try:
by_city.loc["Paris"]
except KeyError as err:
print("KeyError:", err)When you want a placeholder for missing keys, use reindex. It returns exactly the labels you ask for and fills the gaps with NaN.
wanted = ["Lima", "Paris", "Oslo"]
print(by_city.reindex(wanted))Paris gets a row of NaN values. Because NaN is a float, the population_k column becomes float in the result. The .loc version with a list that contains a missing label raises KeyError, so choose based on whether a missing key is an error or an expected case.
Duplicate labels
An index does not have to be unique. Pandas does not stop you from making continent the index, and that changes what a lookup returns.
by_continent = df.set_index("continent")
print(by_continent.index.is_unique)
print(by_continent.loc["South America"])is_unique is False, and .loc["South America"] returns a DataFrame with two rows (Lima and Quito) instead of a Series. Code that assumes a single row will then break in surprising ways, for example when you try to read a scalar from it.
If a key should be unique, ask pandas to check it when you build the index.
try:
df.set_index("continent", verify_integrity=True)
except ValueError as err:
print("ValueError:", err)With verify_integrity=True, set_index raises ValueError when it finds duplicate keys. Use it when the column is supposed to be an identifier, such as an order number or a user ID. The check scans the whole index, so it costs some time on large data.
Slicing by label on an index
With a meaningful index, label slices work as they did in the .loc chapter: both ends are included. For string labels, the index should be sorted first.
ordered = by_city.sort_index()
print(ordered.index.tolist())
print(ordered.loc["Lima":"Pune"])The sorted order is Cairo, Lima, Oslo, Pune, Quito. The slice "Lima":"Pune" returns Lima, Oslo, and Pune. On an unsorted index with duplicate labels, pandas cannot tell where a label slice should start or end and raises KeyError. On a unique but unsorted index, the slice follows the current row order, so the result depends on that order and probably is not what you meant. Calling sort_index() first removes the ambiguity, and it can speed up lookups on large data.
Writing back through the index
A label lookup also works on the left side of an assignment. This follows the same rule as before: do the selection and the assignment in one .loc call.
by_city.loc["Oslo", "population_k"] = 715
by_city.loc[["Pune", "Quito"], "continent"] = "Updated"
print(by_city)Because by_city is its own DataFrame, created by set_index, these writes do not change df.
Getting the column back
The index is not a normal column, so you cannot select it with by_city["city"]. Two methods move data between the index and the columns.
restored = by_city.reset_index()
print(restored.columns.tolist())
kept = df.set_index("city", drop=False)
print(kept.columns.tolist())reset_index()turns the index back into a column and restores a default0, 1, 2, ...index.set_index("city", drop=False)keepscityas a column and also uses it as the index. This is convenient when you need both a lookup key and a filterable column, at the cost of storing the values twice.
The index also has a name. After set_index("city"), by_city.index.name is "city", and reset_index() uses that name for the new column. If an index has no name, reset_index() calls the column index.
When an index is the right choice
| Situation | Better approach |
|---|---|
| Many lookups by one unique key | `set_index`, then `.loc` |
| One-off filter on a column | Boolean mask |
| Filter on several columns or ranges | Boolean mask or `query` |
| Key is not unique and you expect one row | Fix the data, or use a mask |
| You need the key as a normal column too | `set_index(..., drop=False)` or `reset_index()` |
For a single filter, a mask is simpler and does not change the table's shape. The index pays off when you repeat lookups by key, join tables on that key, or want results aligned by label.
Common mistakes
- Forgetting that
set_indexreturns a new object. Writingdf.set_index("city")on its own line changes nothing. Assign the result, or passinplace=True, though assignment is the clearer style. - Expecting
by_city["city"]to work afterset_index. The column is gone. Useby_city.index,reset_index(), ordrop=False. - Assuming a lookup returns a Series. With duplicate labels it returns a DataFrame.
- Mixing up
.locand.ilocafter changing the index.by_city.loc["Lima"]uses the label.by_city.iloc[1]uses the position, and the two agree here only by coincidence of the row order.
Exercise
Using the df from this chapter, write code that makes country the index and then prints the population (in thousands) of Egypt and Peru, in that order. Then explain what .loc["Egypt"] would return on df.set_index("continent") if you used the wrong key, and what happens when you look up "Spain" with .loc on the country-indexed table.
Show answer
Code: by_country = df.set_index("country") followed by print(by_country.loc[["Egypt", "Peru"], "population_k"]). This prints the Series with Egypt (10230) first and Peru (10092) second, because a list of labels returns rows in the requested order. On df.set_index("continent"), the key "Egypt" is not an index label, so .loc["Egypt"] raises KeyError. Looking up "Spain" on the country-indexed table also raises KeyError. To get a NaN row instead, use by_country.reindex(["Spain"]).
Exercise
You run by_continent = df.set_index("continent") and then by_continent.loc["South America", "population_k"]. What type does it return, and how can you make set_index fail instead if continent was meant to be unique?
Show answer
It returns a Series with two values (Lima's 10092 and Quito's 2800), because "South America" appears twice in the index and so the lookup returns every matching row. To make set_index fail on duplicates, call df.set_index("continent", verify_integrity=True), which raises ValueError when it finds duplicate keys.