Sub topic 9
Index alignment: why results contain NaN
This chapter assumes you can create a Series and a DataFrame, know what an Index is, and understand vectorized arithmetic on a single Series. It explains why adding two pandas objects often produces NaN (pandas's marker for a missing value). It also shows how to predict that result and control it.
The rule: labels decide, not positions
In NumPy, a + b adds elements at the same position. In pandas, arithmetic between two objects first aligns them. Alignment means pandas matches values by Index label and only then does the math.
The result's Index is the union of the two indexes. If a label is present on only one side, there is nothing to pair it with, so the result at that label is NaN.
import pandas as pd
a = pd.Series([1, 2, 3], index=["x", "y", "z"])
b = pd.Series([10, 20, 30], index=["y", "z", "w"])
print(a + b) # x: NaN, y: 12.0, z: 23.0, w: NaN
print(a.add(b, fill_value=0)) # x: 1.0, y: 12.0, z: 23.0, w: 30.0Only y and z exist in both Series, so only those get real sums. x exists only in a and w only in b, so both become NaN.
Notice the dtype change. The inputs are int64, but the result is float64 (12.0, not 12). Integer dtypes cannot hold NaN, so pandas converts the result to float. This is a useful clue when you debug: if integers turn into floats after arithmetic, alignment probably introduced missing values.
What happens step by step
Each side is reindexed to the union, and the missing positions are filled with NaN. Then the addition runs. Any arithmetic involving NaN gives NaN, which is why a missing value on either side spoils the result.
Controlling the result with methods
Operators such as + give you no options. The named methods (add, sub, mul, div) accept fill_value. This substitutes a value for a label that is missing on one side before the operation.
a.add(b, fill_value=0)treats a missing side as 0, soxbecomes1 + 0 = 1.- If a label is missing on both sides,
fill_valuecannot help, and the result staysNaN. fill_valuefills only entries that are missing because of alignment on one side. It does not rescue an existingNaNthat appears on both sides.
Choose the fill value to match the operation. For addition, 0 is neutral. For multiplication, use 1, or you will zero out the result.
import pandas as pd
a = pd.Series([1, 2, 3], index=["x", "y", "z"])
b = pd.Series([10, 20, 30], index=["y", "z", "w"])
print(a.mul(b, fill_value=1)) # x: 1.0, y: 20.0, z: 60.0, w: 30.0Alignment in DataFrames
For a DataFrame, pandas aligns on both axes: the row Index and the column labels. A value is computed only where both the row label and the column label exist in both frames.
import pandas as pd
q1 = pd.DataFrame({"sales": [100, 200], "cost": [60, 90]}, index=["north", "south"])
q2 = pd.DataFrame({"sales": [110, 210], "returns": [5, 8]}, index=["south", "east"])
print(q1 + q2)The output has rows east, north, south and columns cost, returns, sales. Only south/sales has a value on both sides (200 + 110 = 310). Every other cell is NaN.
A frequent mistake is to add a Series to a DataFrame and expect it to apply to each row. By default, pandas aligns the Series Index with the DataFrame's columns.
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
s = pd.Series([10, 20]) # index is 0, 1
print(df + s) # columns a, b don't match 0, 1: everything is NaN
print(df.add(s, axis=0)) # match the Series to the row index insteadThe first line gives a frame full of NaN (with extra columns 0 and 1). The second, using axis=0, adds 10 to row 0 and 20 to row 1.
Common causes of unexpected NaN
When a result has more NaN than you expect, check these causes in order.
- Different labels. Inspect
a.indexandb.index, or usea.index.difference(b.index)to list labels that appear only ina. - Same-looking labels with different types. The integer
1and the string"1"are different labels. This often happens after reading a CSV. - Whitespace or case.
"Oslo"and"Oslo "do not match. Clean labels with.str.strip()and.str.lower()first. - Different row order but the same labels. This is not a problem. Alignment matches by label, so order does not matter.
- Existing missing values. Alignment may not be the cause. The data may already contain
NaN. - Duplicate labels. If an Index has repeated labels, alignment can fail or produce more rows than expected. If the two indexes are not identical, a duplicated label can raise an error because pandas cannot decide how to match it.
import pandas as pd
a = pd.Series([1, 2], index=[1, 2])
b = pd.Series([10, 20], index=["1", "2"])
print((a + b).tolist()) # four NaN values: int and str labels never match
print(a.index.difference(b.index).tolist())Opting out of alignment
Sometimes you want positional arithmetic. You have three options.
- Use
.to_numpy()or.valueson one side, which strips the Index:a + b.to_numpy(). The lengths must match, or NumPy raises an error. This gives up the safety of labels, so use it only when you are sure the order is right. - Reset the Index on both sides with
reset_index(drop=True), so both use0, 1, 2, .... - Reindex deliberately with
b.reindex(a.index). This makes the alignment explicit and producesNaNonly for labelsblacks.
import pandas as pd
a = pd.Series([1, 2, 3], index=["x", "y", "z"])
b = pd.Series([10, 20, 30], index=["y", "z", "w"])
print((a + b.to_numpy()).tolist()) # [11, 22, 33], positional
print((a + b.reindex(a.index)).tolist()) # [nan, 12.0, 23.0]The second line shows reindex keeping only a's labels. w is dropped, and x becomes NaN because b has no x.
Dealing with the NaN afterward
Alignment is often the first step in a pipeline, and the NaN it creates is handled with the tools for missing data, which the next chapter covers: isna, fillna, and dropna. A good habit is to choose between two policies up front.
- Missing means zero or neutral. Use
fill_valuein the arithmetic method, as inadd. - Missing means unknown. Leave the
NaNin place so it is visible, and decide later whether to fill or drop.
Do not fill by reflex. Replacing NaN with 0 changes means, sums, and counts, and it hides the fact that a label did not match.
Summary of behaviors
| Situation | Result |
|---|---|
| Label in both objects | Computed normally |
| Label in only one object, using `+` | `NaN` |
| Label in only one object, using `add(fill_value=0)` | The present value is used |
| Label in neither object | Not in the result |
| Integer inputs with unmatched labels | Result becomes `float64` |
| Series plus DataFrame | Series Index aligns with columns by default |
Exercise
Given s1 = pd.Series([5, 6, 7], index=["a", "b", "c"]) and s2 = pd.Series([1, 1, 1], index=["b", "c", "d"]), what does s1.sub(s2, fill_value=0) return, and what is its dtype?
Show answer
The index is a, b, c, d. Values are a: 5.0 (5 - 0), b: 5.0 (6 - 1), c: 6.0 (7 - 1), d: -1.0 (0 - 1). The dtype is float64, because alignment introduced missing entries before they were filled, so the result is converted to float.
Exercise
You run df + s, where df has columns "a" and "b" and s has the default index 0, 1. The result is full of NaN. How do you add s down the rows instead?
Show answer
Use df.add(s, axis=0). By default pandas aligns the Series Index with the DataFrame columns. Passing axis=0 aligns it with the row Index.