Sub topic 6
Index alignment: what vectorised operations match on
This chapter assumes you can build a DataFrame and Series, and that you know column arithmetic from earlier chapters. Here you will learn that pandas matches values by index label, not by position, and how that causes common bugs.
Labels decide which values pair up
When you combine two Series with +, * or a comparison, pandas first aligns them on their index. It pairs values that share the same label. It does not pair the first with the first.
import pandas as pd
a = pd.Series([1, 2, 3], index=[0, 1, 2])
b = pd.Series([10, 20, 30], index=[2, 1, 0])
print(a + b)The output is 11, 22, 33 for labels 0, 1, 2. Label 0 in a (value 1) pairs with label 0 in b (value 30), giving 31. The result is therefore:
0 31
1 22
2 13
dtype: int64Position played no part. Within one DataFrame this is rarely a problem, because columns share the same index. It matters when two objects come from different sources.
Labels that do not match give NaN
If a label exists on only one side, the result for that label is NaN (missing value).
x = pd.Series([1, 2, 3], index=["a", "b", "c"])
y = pd.Series([10, 20, 30], index=["b", "c", "d"])
print(x + y)a NaN
b 12.0
c 23.0
d NaN
dtype: float64The result has the union of both indexes. Integers also became floats, because NaN is a float value. If you want a missing label treated as zero, use the method form with fill_value:
print(x.add(y, fill_value=0))A common bug: filtered data
Filtering keeps the original labels. Combining a filtered Series with a full one does not shift anything.
df = pd.DataFrame({"price": [10.0, 20.0, 15.0, 8.0], "qty": [3, 1, 4, 2]})
big = df[df["qty"] >= 2] # labels 0, 2, 3
discount = pd.Series([0.1, 0.2, 0.3]) # labels 0, 1, 2
big_price = big["price"] * (1 - discount)
print(big_price)Labels 1 and 3 each appear on only one side, so they give NaN. The code ran without error but the result is wrong for those rows. Two fixes are common:
- Build the second Series with the right index, for example
discount.index = big.index. - Drop the labels and use positions:
big["price"].to_numpy() * (1 - discount.to_numpy()). This requires the lengths to match exactly.
Positional matching is only safe when you are sure the rows line up.
Duplicate labels and mismatched indexes
Duplicate index labels can make alignment fail or multiply rows. If you see cannot reindex on an axis with duplicate labels, check df.index.is_unique. A fresh reset_index(drop=True) often restores a clean 0..n-1 index.
Comparisons between two Series raise an error if their indexes differ, for example Can only compare identically-labeled Series objects. Use .equals(), or align first with a.align(b).
Assignment aligns too
Assigning a Series to a column also aligns on the index.
scores = pd.DataFrame({"id": [1, 2, 3]}, index=[5, 6, 7])
scores["bonus"] = pd.Series([0.5, 0.7, 0.9])
print(scores)The new Series has labels 0, 1, 2, and scores has 5, 6, 7. No labels match, so every bonus value is NaN. Assigning a list or NumPy array skips alignment and uses position instead.
Exercise
You compute df["price"] * factors, where df was filtered with a boolean mask and factors is a new Series with the default index 0..n-1. Some results are NaN. Why, and how do you fix it?
Show answer
The filtered df keeps its original labels, so they no longer match the labels 0..n-1 of factors. Labels present on only one side give NaN. Fix it by giving factors the same index as df (factors.index = df.index), or by calling reset_index(drop=True) on the filtered frame, or by using to_numpy() on both when you are sure the rows line up.