skip to content

In pandas, why does adding two stores' monthly revenue Series with s1 + s2 return NaN for some months, and what does add(fill_value=0) change?

level: middleimportance: must knowfreq 70%

answer

  1. labels pair values, not positions
  2. result carries the union
  3. the flex method fills one side
  4. both sides missing stays missing

basics

~20 s

pandas pairs values by index label and returns the union of both indexes, so a month only one Series has gets NaN. add(fill_value=0) treats the missing side as 0, except where both sides are missing.

solid answer

~50 s

Arithmetic between two pandas Series aligns on the index first. When the indexes are not equal, pandas performs an outer join: the result is labelled by the union of both indexes (sorted when the labels can be compared), and a label found on only one side has no partner, so its result is `NaN`. A month the south store did not report therefore turns `north + south` into `NaN` there, and int64 inputs come back as `float64` because NaN needs a float. `north.add(south, fill_value=0)` substitutes 0 for the missing operand, at alignment gaps and at values that were already NaN, before adding; where *both* sides are missing the result stays `NaN`. The result is still `float64`, because alignment runs before the fill. Order never matters: the same labels in a different order still pair correctly.

code

python · 13 lines
python
import pandas as pd

north = pd.Series([120, 135, 150], index=["2026-01", "2026-02", "2026-03"], name="revenue")
south = pd.Series([90, 110], index=["2026-02", "2026-03"], name="revenue")

total = north + south
print(total.to_dict())    # {'2026-01': nan, '2026-02': 225.0, '2026-03': 260.0}
print(total.dtype)        # float64

filled = north.add(south, fill_value=0)
print(filled.to_dict())   # {'2026-01': 120.0, '2026-02': 225.0, '2026-03': 260.0}

print(north.index.symmetric_difference(south.index).tolist())  # ['2026-01']

go deeper

for a junior

Recall that Series arithmetic pairs values by index label and returns the union of labels, with NaN where one side has no value.

for a middle

Explain the order inside add(fill_value=...): align, fill only where one side is missing, then add; and why the result is float64 either way.

for a senior

Show you ask what a gap means before filling it, and that you check index.symmetric_difference when a sum is unexpectedly NaN-heavy.

for a principal

Weigh where a team decides what missing means: filling at the arithmetic call scatters that decision, while conforming inputs to an agreed label set once keeps it reviewable.

## How pandas pairs values in Series arithmetic A pandas `Series` is a column of values plus an **Index** of labels. When two Series meet in an arithmetic operator such as `+`, pandas does not pair them by position the way a NumPy array would. It first **aligns** them on their labels: - If the two indexes are **equal**, the values are combined directly. - Otherwise pandas performs an **outer join** of the two indexes. The result is labelled by their **union**, sorted when the labels can be compared, and each operand is conformed to that union. - A label present on only one side has **no partner**; the conformed operand holds `NaN` there, and anything plus `NaN` is `NaN`. So in the two-store case, `north + south` gives a number for every month both stores reported and `NaN` for every month only one store reported. Nothing warns you; the gap is visible only in the result. ## Why the gaps also change the dtype Alignment inserts `NaN` into the operand that lacks the label. A NumPy-backed `int64` column cannot hold `NaN`, so the conformed operand becomes `float64`, and so does the result. Two integer Series with mismatched labels therefore produce **`float64`**, even at the labels that matched. The result's `name` is kept when both inputs share it and becomes `None` when they differ. ## What add(fill_value=0) does Every arithmetic operator has a **flex method** twin that takes extra arguments. The one that matters here is `fill_value`: | Operator | Flex method | |---|---| | `a + b` | `a.add(b, fill_value=...)` | | `a - b` | `a.sub(b, fill_value=...)` | | `a * b` | `a.mul(b, fill_value=...)` | | `a / b` | `a.div(b, fill_value=...)` | `north.add(south, fill_value=0)` works in a fixed order: 1. Align the two Series with an outer join, exactly as `+` does. 2. Wherever **exactly one** operand is missing, replace the missing one with `0`. This covers alignment gaps **and** values that were already `NaN` in the input. 3. Where **both** operands are missing, leave them alone, so the result stays `NaN`. 4. Add. The result is still `float64`: the fill happens after alignment has already converted the column. ## Tracing the two-store example Take `north` with labels `2026-01`, `2026-02`, `2026-03` and `south` with only `2026-02` and `2026-03`, both `int64`. 1. The indexes are not equal, so pandas joins them: the union is `2026-01`, `2026-02`, `2026-03`. 2. `north` already has every label and keeps its values. `south` is conformed to the union and gets `NaN` at `2026-01`, which makes it `float64`. 3. `north + south` adds element by element: `2026-01` is `120 + NaN = NaN`, the other two months are real sums. 4. `north.add(south, fill_value=0)` repeats step 1 and 2, then replaces the single missing operand at `2026-01` with 0, so the total there is `120.0`. The same rule holds for a `Series` with a `MultiIndex`, where `level=` on the flex method aligns on one level only, and for two DataFrames, which align on rows **and** columns. ## Choosing the right fix `fill_value=0` is correct only when a missing month genuinely means zero revenue. Ask what the gap means before choosing: - **Missing means zero** (the store was closed): `add(fill_value=0)`. - **Missing means unknown** (the report has not arrived): keep the `NaN`, so the total is visibly incomplete. - **Only common months matter**: drop the `NaN` with `dropna()`, or align with an inner join first. - **Labels that should match but do not**: inspect `north.index.symmetric_difference(south.index)`. A label like `"2026-1"` against `"2026-01"`, or strings against a datetime index, produces an all-`NaN` result that no fill value should hide. For division, a `fill_value` of 0 is rarely what you want; a zero denominator yields `inf`, not a sensible ratio. ## Common misreadings - **"pandas adds by position when the lengths match."** It aligns by label whenever the indexes differ, whatever the lengths. - **"fill_value fills only the alignment gaps."** It also fills `NaN` that was already in one operand. - **"fill_value=0 turns every NaN into a number."** A label missing on both sides stays `NaN`. - **"The result keeps int64 if I fill."** Alignment has already made it `float64`.

  • Two pandas Series hold the same twelve month labels, but one is in reverse order; what does s1 + s2 give?
    The correct sums. The indexes are not equal, so pandas aligns them by label and adds January to January; no `NaN` appears because every label has a partner. Only labels that genuinely differ, such as a typo or strings against a datetime index, produce `NaN`.
  • How do you add the two stores' Series by position on purpose, ignoring the labels?
    Strip the labels from one side, for example `north + south.to_numpy()`, which requires equal lengths and pairs the n-th values. Do this only when position is the real key; if the labels disagree, positional pairing hides the mismatch instead of fixing it.

Two shops' ledgers totalled by matching month headings rather than line numbers: a month only one ledger lists gets a blank total, unless you agree that a blank on one side counts as zero.

  • pandas adds two Series position by position when their lengths match
  • add(fill_value=0) turns every NaN in the result into a number
  • fill_value only fills the gaps created by alignment
  • The sum of two int64 Series stays int64 even when labels differ
  • Unequal indexes make s1 + s2 raise an error