Sub topic 6
Index alignment: what vectorised operations match on
This chapter assumes you can build DataFrames and Series, select rows with boolean masks, and read a basic arithmetic expression such as df["price"] * df["qty"]. Earlier chapters used column arithmetic as if it matched values row by row. It doesn't. pandas matches values by index label, and this explains several results that look like bugs, especially unexpected NaN values and wrong numbers after filtering or sorting.
Labels, not positions
A loop over rows works by position: the first row, then the second. A vectorised pandas operation between two objects first aligns them. It compares their indexes and pairs up values that share the same label. Only then does it compute.
import pandas as pd
a = pd.Series([10, 20, 30], index=["x", "y", "z"])
b = pd.Series([1, 2, 3], index=["z", "x", "y"])
print(a + b)x 12
y 23
z 31
dtype: int64The second Series lists its labels in a different order. pandas still pairs x with x, y with y and z with z. A positional library such as NumPy would have computed 10 + 1, 20 + 2 and 30 + 3.
What happens to labels that don't match
The result's index is the union of both indexes. A label that exists on only one side has no partner, so the result is NaN.
c = pd.Series([1, 2], index=["x", "w"])
print(a + c)w NaN
x 11.0
y NaN
z NaN
dtype: float64Two things follow from this output:
- The union is sorted when the indexes differ, so
wappears first. - The dtype changed from
int64tofloat64, because integers cannot holdNaN. A silent dtype change is often the first hint that alignment produced missing values.
If a missing label should count as zero, use the method form of the operator and pass fill_value.
print(a.add(c, fill_value=0))w 2.0
x 11.0
y 20.0
z 30.0
dtype: float64fill_value applies only where one side is missing. If both sides are missing, the result is still NaN. The same options exist as sub, mul, div and the other arithmetic methods.
The flow below shows the decision pandas makes for every binary operation.
When the indexes are identical, pandas skips the matching work. This is one reason operations on frames that share an index are fast.
The common trap: filtering, then combining
Boolean filtering keeps the original labels. A filtered DataFrame therefore has gaps in its index, and this matters as soon as you combine it with something that has a fresh 0, 1, 2 index.
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.5, 0.25, 0.125]) # labels 0, 1, 2
print(big["price"] * discount)0 5.00
1 NaN
2 3.75
3 NaN
dtype: float64You probably meant "the first discount goes to the first big order". pandas instead matched label 0 with label 0 and label 2 with label 2. The 0.25 discount at label 1 found no price, and the price at label 3 found no discount.
There are three ways to fix this. Choose the one that matches your intent.
- Give the discounts the labels of the rows they belong to. This is the best choice when the labels carry meaning.
- Reset the index on the filtered frame so both sides use
0, 1, 2. - Drop to NumPy arrays and accept positional matching. Use this only when you are certain the order is right.
# 1. Relabel the discounts
discount.index = big.index
print(big["price"] * discount)
# 2. Reset the filtered frame's index (the old labels are discarded)
fresh = big.reset_index(drop=True)
discount_by_position = pd.Series([0.5, 0.25, 0.125])
print(fresh["price"] * discount_by_position)
# 3. Positional, no alignment at all
print(big["price"].to_numpy() * discount_by_position.to_numpy())All three produce 5.0, 3.75 and 1.0 for the three rows, but they carry different labels in the result. The third returns a bare array with no labels, so you must wrap it in a Series with the right index if you want to assign it back.
Assigning a column also aligns
Assignment with df["new"] = series aligns the Series to df.index. Rows with no matching label get NaN, and labels that aren't in df are dropped.
labels = pd.Series(["a", "b", "c"], index=[2, 0, 1])
df["label"] = labels
print(df) price qty label
0 10.0 3 b
1 20.0 1 c
2 15.0 4 a
3 8.0 2 NaNThe Series was in a different order and shorter than the frame. Alignment placed each value on the right row anyway and left the last row empty.
This is why results from groupby(...).transform(...) assign cleanly. A transform result carries the same index as the original rows, so it lands on the correct rows even if the frame was sorted or filtered earlier.
Compare that with assigning a NumPy array, which skips alignment entirely.
ranked = df.sort_values("price") # same labels, new row order
df["wrong"] = ranked["qty"].to_numpy() # positional: values land on the wrong rows
df["right"] = ranked["qty"] # aligned: values follow their labelsAfter sort_values, the rows are reordered but keep their labels. The right column matches each quantity with its own row. The wrong column is the sorted quantities pasted down the unsorted frame. Nothing raises an error, so this bug can survive for a long time.
DataFrames align on columns too
For two DataFrames, pandas aligns on both the row index and the column labels.
left = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
right = pd.DataFrame({"b": [10, 20], "c": [30, 40]})
print(left + right) a b c
0 NaN 13 NaN
1 NaN 24 NaNOnly column b exists in both, so only b has numbers. Columns a and c are all NaN. This often happens after a rename, a typo in a column name, or a stray space in a header.
A DataFrame combined with a Series is a subtler case. By default, the Series index is matched against the column labels, so the Series acts as a row that is broadcast down the frame. To subtract a column from every other column, tell pandas to align on the rows with axis=0.
numbers = df[["price", "qty"]]
# Aligns the Series index (0..3) to the column names: not what you want
bad = numbers - df["price"]
# Aligns the Series index to the row labels
good = numbers.sub(df["price"], axis=0)
print(good) price qty
0 0.0 -7.0
1 0.0 -19.0
2 0.0 -11.0
3 0.0 -6.0The operator form - has no axis argument, so use the method form (sub, add, mul, div) whenever you need to choose the axis.
Duplicate labels
Alignment assumes each label identifies one row. If an index has repeated labels, pandas can't pair values one to one when the two indexes differ. It pairs every repeated label on the left with every repeated label on the right.
s1 = pd.Series([1, 2], index=["a", "a"])
s3 = pd.Series([10, 20, 30], index=["a", "a", "b"])
print(len(s1 + s3))5Neither input has five entries. The two a rows on the left each pair with the two a rows on the right, which gives four rows. Label b adds a fifth, which is NaN. With large frames, this can multiply the row count and exhaust memory.
A common source of duplicate labels is pd.concat on frames that each have their own 0, 1, 2... index. Pass ignore_index=True when the old labels carry no meaning, and check df.index.is_unique before you rely on alignment.
Checks that catch alignment problems early
| Symptom | Likely cause | What to check |
|---|---|---|
| Unexpected `NaN` in a result | Labels don't overlap, often after filtering | `a.index.equals(b.index)` |
| Integer column became float | Missing labels introduced `NaN` | Result's `isna().sum()` |
| Result has more rows than either input | Duplicate labels on both sides | `index.is_unique` |
| `ValueError: Can only compare identically-labeled Series objects` | `==` or `<` on Series with different indexes | Align first with `a.align(b)` or reindex |
| Right numbers on the wrong rows | A NumPy array was assigned after sorting | Assign the Series, not `.to_numpy()` |
| A whole DataFrame column is `NaN` | Column labels differ (typo, whitespace) | Compare `left.columns` and `right.columns` |
Two tools help you control alignment explicitly:
reindexchanges an object to match a given set of labels, insertingNaNfor new ones:b.reindex(a.index).a.align(b, join="inner")returns both objects restricted to the labels they share, so a later operation has noNaNfrom mismatches.
aligned_a, aligned_b = a.align(c, join="inner")
print(aligned_a + aligned_b)x 11
dtype: int64Using an inner join keeps only label x, and the integer dtype is preserved.
Why this helps vectorised code
Alignment is also the reason many vectorised rewrites are safe. A loop that fetches "the row with this key" has to implement matching by hand. In a vectorised expression, pandas does the matching on the index. Later chapters use this directly: transform returns a result that lines up with the original rows, and map and merge look values up by label or key.
Exercise
Given x = pd.Series([1, 2, 3], index=[0, 1, 2]) and y = pd.Series([10, 20, 30], index=[1, 2, 3]), what is x + y? Then write an expression that gives [11, 22, 33] by pairing the values by position, and another that treats a missing label as zero.
Show answer
x + y has labels 0, 1, 2, 3 with values NaN, 12.0, 23.0, NaN. Labels 1 and 2 exist on both sides (2 + 10 and 3 + 20 are matched by label, giving 12 and 23). Labels 0 and 3 exist on one side only. Positional pairing: x.to_numpy() + y.to_numpy() gives [11, 22, 33]. Treating a missing label as zero: x.add(y, fill_value=0) gives 1.0, 12.0, 23.0, 30.0.
Exercise
A frame orders has index 0 to 5. You write late = orders[orders["days"] > 5], compute penalty = pd.Series([2.0, 4.0, 6.0]) with a fresh index, and run late["fee"] = penalty. Why are most of the new values NaN or on the wrong rows, and how do you assign the penalties to the late rows in order?
Show answer
The assignment aligns penalty to the labels of late, which are the original labels such as 1, 3 and 4, not 0, 1, 2. Only labels that appear in both are filled, and a penalty can land on a row you didn't intend. To assign in order, either set penalty.index = late.index before assigning, or use late = late.assign(fee=penalty.to_numpy()) after confirming the lengths match. Using .copy() on the filtered frame also avoids a SettingWithCopyWarning.