Sub topic 2
The Index: how pandas identifies rows
This chapter assumes you can run Python, know what a Series is (values plus a label for each value), and have seen a small DataFrame. Here you learn what the Index is, how it differs from position, and where it causes surprises.
What the Index is
Every Series and DataFrame has an Index, an ordered collection of labels, one per row. Pandas uses labels, not positions, to identify data. This is why s["b"] works and why arithmetic between two objects matches rows by label.
import pandas as pd
s = pd.Series([10, 20, 30], index=["a", "b", "c"], name="score")
print(s.index) # Index(['a', 'b', 'c'], dtype='object')
print(s.index.tolist()) # ['a', 'b', 'c']
print(s["b"]) # 20, by label
print(s.iloc[0]) # 10, by positionIf you give no index, pandas creates a RangeIndex of 0, 1, 2, .... Those numbers are still labels. They only look like positions.
Labels versus positions
Label and position agree only by accident. After filtering or sorting, the labels keep their original values while positions restart at 0.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8]})
big = df[df["pop_m"] > 2]
print(big)
print(big.loc[1, "city"]) # Lima, label 1
print(big.iloc[0]["city"]) # Lima, position 0Here big has labels 1, 2, 3. Asking for label 0 with big.loc[0] raises a KeyError, because that row was removed.
Choosing and changing the Index
You can turn a column into the Index with set_index and move it back with reset_index. A column that identifies each row, such as a city name, is a good Index.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"],
"pop_m": [0.7, 10.7, 3.1]})
by_city = df.set_index("city")
print(by_city.loc["Lima", "pop_m"]) # 10.7
flat = by_city.reset_index() # city is a column again
print(flat.columns.tolist()) # ['city', 'pop_m']Both methods return a new object. The original df is unchanged.
Common errors
- Duplicate labels are allowed.
s.loc["a"]then returns a Series, not a single value. Check withs.index.is_unique. - Integer labels hide the label/position difference. Use
locfor labels andilocfor positions so your intent is explicit. - Index values are immutable. You cannot assign
s.index[0] = "z". Replace the whole index withs.index = [...]or userename. - A new index must match the length. Assigning a list of the wrong length raises a
ValueError.
Exercise
A DataFrame df has the default index 0 to 3. You run sub = df[df["pop_m"] > 3], and the rows with labels 1 and 2 remain. What does sub.iloc[0] return, and what does sub.loc[0] do?
Show answer
sub.iloc[0] returns the first remaining row, which has label 1, because iloc uses position. sub.loc[0] raises a KeyError, because label 0 was filtered out.