Lesson 1 of 9 · 22m
Indexes, Labels, and the Alignment Trap
Why pandas aligns on index labels instead of positions, when that saves you, and when it quietly fabricates NaNs.
The fastest way to be dangerous with pandas is to treat a DataFrame like a spreadsheet with rows numbered 0..n. pandas is closer to a labeled tensor: every Series carries an index, and most binary operations align on those labels before they touch the values. That design is brilliant for time series and joins. It also means code can run cleanly while producing nonsense.
Labels first, positions second
import pandas as pd
a = pd.Series([10, 20], index=["us-east", "eu-west"])
b = pd.Series([1, 2], index=["eu-west", "us-east"])
print(a + b)The result is not [11, 22]. It aligns by label:
eu-west 22
us-east 12
dtype: int64That is correct if the labels mean "same entity." It is catastrophic if you meant "first element plus first element." When indexes disagree partially, pandas inserts NaN instead of raising. Silent missingness is worse than an exception.
The index is metadata with behavior
An index can be integers, timestamps, strings, or a MultiIndex. It controls lookup speed, alignment, and output shape. df.reset_index() demotes labels into ordinary columns; df.set_index("order_id") does the reverse. Neither is cosmetic. If you index by customer_id and then concatenate two extracts that reuse the same IDs, you have created duplicate labels — valid, but now loc may return multiple rows.
Positional indexing still exists, but it is explicit
df.iloc[0] # first row by position
df.loc[order_id] # row(s) by label
df.iloc[0:10, 2:5] # row/column positions
df.loc[:, ["sku", "units"]] # all rows, columns by labelUse iloc when position is the meaning ("first ten rows after sorting"). Use loc when the label is the meaning ("this customer," "this timestamp"). If you find yourself translating labels into integer positions in application logic, you are probably fighting the data model.
Alignment shows up everywhere
Arithmetic between Series, assigning a Series into a DataFrame, reindexing, and time-series operations all align first. A common incident pattern looks like this:
df["refunded"] = refund_flags # aligns on refund_flags.index, not row orderIf refund_flags came from a filtered or resampled frame, every unmatched row becomes missing. Before assigning, either verify indexes or remove alignment deliberately:
df["refunded"] = refund_flags.to_numpy() # positional assignment; be sure order is rightField notes
- After any merge, concat, filter, or resample, ask: what is the index now?
df.index.is_uniqueis cheap insurance before using labels as keys.NaNappearing after arithmetic usually means misalignment, not missing source data.- Prefer meaningful indexes for lookup tables; prefer a plain RangeIndex for row-oriented pipelines.
- If two indexes have different dtypes (
"42"vs42), alignment fails silently in exactly the way you expect least.
Was this lesson helpful?