Working with the Index
Every Series and DataFrame has an index: the row labels on the left. Until now we have mostly used the default 0, 1, 2… index, but choosing a meaningful index (a product code, a date, a country) makes lookups, alignment and plotting much easier.
set_index(): turn a column into the index
import pandas as pd
countries = pd.DataFrame({
"code": ["FR", "JP", "BR", "KE"],
"capital": ["Paris", "Tokyo", "Brasília", "Nairobi"],
"area_km2": [551695, 377975, 8515767, 580367],
})
by_code = countries.set_index("code")
print(by_code)
print(by_code.loc["JP", "capital"]) capital area_km2
code
FR Paris 551695
JP Tokyo 377975
BR Brasília 8515767
KE Nairobi 580367
Tokyo
The code column moved to the left and became the row labels, so loc["JP"] finds Japan directly. The index name (code) is printed above the labels.
reset_index(): back to a column
reset_index() does the opposite: it moves the index back into a regular column and restores the 0, 1, 2… numbering. With drop=True the old index is thrown away instead:
import pandas as pd
by_code = pd.DataFrame({
"capital": ["Paris", "Tokyo", "Brasília"],
"area_km2": [551695, 377975, 8515767],
}, index=pd.Index(["FR", "JP", "BR"], name="code"))
print(by_code.reset_index())
print(by_code.sort_values("area_km2").reset_index(drop=True)) code capital area_km2
0 FR Paris 551695
1 JP Tokyo 377975
2 BR Brasília 8515767
capital area_km2
0 Tokyo 377975
1 Paris 551695
2 Brasília 8515767
You will call reset_index() a lot after groupby(), which puts the group keys into the index.
Alignment uses the index
When pandas combines two objects, it matches rows by index label. A good index makes this work for you; a mismatched one produces NaN:
import pandas as pd
stock = pd.Series({"apple": 30, "kiwi": 12, "lime": 50})
sold_today = pd.Series({"lime": 8, "apple": 5})
remaining = stock.sub(sold_today, fill_value=0)
print(remaining)
print(stock - sold_today)apple 25.0
kiwi 12.0
lime 42.0
dtype: float64
apple 25.0
kiwi NaN
lime 42.0
dtype: float64
The sub method with fill_value=0 treats a missing label as 0, so kiwi keeps its 12. The plain - operator gives NaN for kiwi because it has no partner.
reindex(): conform to a new set of labels
reindex() returns the data rearranged to a given list of labels. Labels that didn't exist get NaN (or a fill_value):
import pandas as pd
visits = pd.Series({"Mon": 120, "Wed": 95, "Fri": 140})
week = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(visits.reindex(week))
print(visits.reindex(week, fill_value=0).to_list())Mon 120.0
Tue NaN
Wed 95.0
Thu NaN
Fri 140.0
dtype: float64
[120, 0, 95, 0, 140]
This is the standard way to fill in gaps such as days with no sales.
Inspecting and renaming the index
import pandas as pd
scores = pd.DataFrame({"pts": [12, 9, 15]}, index=["red", "blue", "green"])
print(scores.index)
print(scores.index.to_list())
print("blue" in scores.index)
scores.index.name = "team"
print(scores.rename(index={"red": "crimson"}))
print(scores.sort_index())Index(['red', 'blue', 'green'], dtype='object')
['red', 'blue', 'green']
True
pts
team
crimson 12
blue 9
green 15
pts
team
blue 9
green 15
red 12
| Method | What it does |
|---|---|
set_index("col") |
make a column the index |
reset_index() |
move the index back into a column |
reindex(labels) |
rearrange/fill to exactly these labels |
sort_index() |
sort rows by their labels |
rename(index={...}) |
rename individual labels |
df.index.name = "x" |
name the index |
df.index.is_unique |
check that no label repeats |
Note: An index does not have to be unique, but duplicated labels make
locreturn several rows where you might expect one. Check withdf.index.is_uniqueafterset_index.
Test yourself
What does df.set_index("id") do?
- Sorts by id
- Makes the id column the row labels
- Deletes the id column
- Adds a new id column
What does reset_index(drop=True) do?
- Moves the index into a column
- Discards the current index and numbers rows 0, 1, 2…
- Deletes all rows
- Drops rows with missing labels
pd.Series({"a": 1}).reindex(["a", "b"]) gives which value for b?
- 0
- 1
- NaN
- An error