Sub topic 2
The Index: how pandas identifies rows
This chapter assumes you can read a pandas Series and know basic Python lists and dictionaries. If pd.Series([10, 20, 30]) is new to you, review the previous chapter first.
Every Series has an Index, an ordered collection of labels with one label per value. The Index decides what "the same row" means in pandas. Selection, arithmetic, joins and grouping all depend on it.
What the Index is
A Series is two parallel pieces of data. The values are stored in a NumPy-style array. The Index stores the labels. The two are tied by position: the label at position 0 names the value at position 0.
import pandas as pd
s = pd.Series([10, 20, 30])
print(s.index) # RangeIndex(start=0, stop=3, step=1)
t = pd.Series([10, 20, 30], index=["a", "b", "c"])
print(t.index) # an Index holding the strings a, b, cIf you give no index, pandas builds a RangeIndex (0, 1, 2, ...). It stores only a start, a stop and a step, so it uses almost no memory however long it is.
pandas does the label-to-position step with a lookup structure that it builds on demand. Looking up a label is therefore much cheaper than scanning the values.
Kinds of Index
The kind of Index you get depends on the labels you provide.
| Index type | Typical labels | Notes |
|---|---|---|
| `RangeIndex` | 0, 1, 2, ... | Default. Compact. |
| `Index` | strings, integers, floats | General purpose. |
| `DatetimeIndex` | timestamps | Supports date-aware selection and slicing. |
| `CategoricalIndex` | few repeated labels | Saves memory. |
| `MultiIndex` | tuples of labels | Several levels per row. Covered later. |
You can also build an Index directly and give it a name. The name travels with the Index and appears when you print the Series.
import pandas as pd
idx = pd.Index(["a", "b", "c"], name="letter")
s = pd.Series([10, 20, 30], index=idx, name="score")
print(s)The printed output shows letter above the labels and Name: score below the values. The index name describes the labels. The Series name describes the values. They are separate attributes.
The Index is immutable
You can replace a Series' whole index, but you cannot change one label in place.
import pandas as pd
idx = pd.Index(["a", "b", "c"])
try:
idx[0] = "z"
except TypeError as e:
print(e) # Index does not support mutable operations
s = pd.Series([10, 20, 30], index=idx)
s.index = ["x", "y", "z"] # replacing the whole index is allowed
print(s.index.tolist()) # ['x', 'y', 'z']Immutability matters because pandas can safely share one Index among many objects, and it can cache the lookup structure. To change a single label, build a new list of labels or use s.rename({"a": "z"}). Both give you a new object with a new Index.
Labels survive filtering
Row labels are not renumbered when you select a subset. They stay attached to the values they identified. This is the main difference between an Index and a position.
import pandas as pd
s = pd.Series([5, 6, 7, 8], index=[10, 11, 12, 13])
big = s[s > 6]
print(big)
# 12 7
# 13 8
# dtype: int64
print(big.loc[12]) # 7, by label
print(big.iloc[0]) # 7, by positionloc uses labels and iloc uses integer positions. Both appear here only as a preview, and the selection chapter covers them in full. In big, the label 12 sits at position 0. If you mix the two ideas up, you will read the wrong row without any error.
The integer-label trap
When the labels are integers, plain [] indexing on a Series treats the integer as a label, not a position.
import pandas as pd
s = pd.Series([5, 6, 7, 8], index=[10, 11, 12, 13])
try:
s[0]
except KeyError:
print("no label 0") # [] looked for the label 0, which does not exist
print(s.iloc[0]) # 5, the first value by positionThis is why pandas documentation recommends loc for labels and iloc for positions. They state your intent, and they behave the same whatever kind of Index you have.
Duplicate labels are allowed
pandas does not require labels to be unique. A label that appears twice returns every matching row.
import pandas as pd
d = pd.Series([1, 2, 3], index=["a", "a", "b"])
print(d.index.is_unique) # False
print(d["a"]) # a Series with two rows
print(d["b"]) # 3, a single scalarThe return type depends on the data: a scalar when the label is unique, and a Series when it repeats. Code that assumes a scalar can break when new data introduces a duplicate. Duplicates also cause errors elsewhere, for example when you reindex or align. Check index.is_unique whenever you load labels you did not create yourself.
Membership tests check labels
The in operator on a Series tests the Index, not the values. This resembles a Python dictionary, whose in tests keys.
import pandas as pd
t = pd.Series([10, 20, 30], index=["a", "b", "c"])
print("b" in t) # True, "b" is a label
print(20 in t) # False, 20 is a value, not a label
print(20 in t.values) # True
print(t.isin([20, 30]).tolist()) # [False, True, True]Use isin to test values elementwise. It returns a boolean Series with the same Index.
Changing the Index
Three operations cover most needs.
- Assign a new index.
s.index = [...]replaces every label. The new list must have the same length as the Series. - Reset the index.
s.reset_index(drop=True)discards the labels and restores a freshRangeIndex. Withoutdrop=True, the old labels become a column and you get a DataFrame. - Reindex.
s.reindex(new_labels)builds a new Series that follows the labels you give it, in that order.
import pandas as pd
t = pd.Series([10, 20, 30], index=["a", "b", "c"])
r = t.reindex(["c", "a", "d"])
print(r)
# c 30.0
# a 10.0
# d NaN
# dtype: float64
print(t.reset_index(drop=True).index) # RangeIndex(start=0, stop=3, step=1)reindex pulls existing values to the labels you name. Label d does not exist in t, so pandas fills it with NaN, which stands for a missing value. Because NaN is a float, the whole Series changes from integers to floats. The index alignment and missing data chapters return to both effects.
Do not confuse reindex with assigning s.index = [...]. Assignment relabels the same values by position. reindex moves values to match labels.
Why this design matters
Because values carry their labels, pandas can combine two objects by matching labels instead of positions. Adding two Series, as a later chapter shows, pairs up equal labels and produces NaN where one side lacks a label. A DataFrame is built the same way: its columns share one row Index. Understanding the Index now makes those chapters follow from one rule: labels identify rows, and positions only describe where rows currently sit.
Common mistakes
- Using
s[0]on an integer-labeled Series and getting aKeyError, or worse, a different row than expected. Preferlocandiloc. - Assuming labels are unique, then getting a Series where you expected a scalar.
- Expecting
into search values. - Trying to edit one label in place instead of building a new Index.
- Treating the labels after a filter as positions from 0.
Exercise
Given s = pd.Series([1, 2, 3, 4], index=[3, 2, 1, 0]), what do s[0], s.loc[0] and s.iloc[0] return, and why?
Show answer
s[0] and s.loc[0] both return 4. With an integer Index, [] treats 0 as a label, and the label 0 is attached to the value 4. s.iloc[0] returns 1 because it uses position, and the first value sits at position 0 even though its label is 3.
Exercise
A Series t has the index ["a", "b", "c"] and the values 10, 20, 30. What does t.reindex(["b", "d"]) return, and what is the dtype of the result?
Show answer
It returns a Series with label b holding 20.0 and label d holding NaN. The dtype is float64, because NaN is a float and pandas converts the integers to hold it.