skip to content

In pandas, what does DataFrame.reindex do when a product table indexed by SKU is conformed to a full catalogue list of SKUs?

level: middleimportance: should knowfreq 50%

answer

  1. conform to a given label list
  2. new labels get a filler
  3. unlisted labels disappear
  4. an int column may turn float
  5. repeats make it refuse

basics

~20 s

reindex returns a frame with exactly the listed labels, in list order: existing SKUs keep their rows, new SKUs get NaN (or fill_value), and SKUs absent from the list are dropped. It matches labels; it never renames them.

solid answer

~40 s

`products.reindex(catalogue)` conforms the frame to the catalogue list: one row per listed label, in that order. A SKU already in the Index keeps its row, a SKU new to the frame gets `NaN` in every column, so an int64 `stock` column becomes `float64`, and a SKU the list leaves out is dropped. `fill_value=0` fills new rows with 0 instead and keeps `stock` as int64. `method="ffill"`, `"bfill"` or `"nearest"` fill from neighbouring labels, but only on a monotonic Index. `reindex` never changes a label: to relabel use `rename`, to promote a column use `set_index`. It raises `ValueError: cannot reindex on an axis with duplicate labels` when the frame's Index has repeats.

code

python · 15 lines
python
import pandas as pd

products = pd.DataFrame(
    {"sku": ["A-100", "A-200", "B-300"], "stock": [5, 0, 12], "price": [9.5, 4.0, 20.0]}
).set_index("sku")
catalogue = ["A-100", "A-250", "B-300"]      # A-200 is not listed, A-250 is new

full = products.reindex(catalogue)
print(full.index.tolist())                   # ['A-100', 'A-250', 'B-300']
print(full["stock"].tolist())                # [5.0, nan, 12.0]
print(full["stock"].dtype)                   # float64

zero = products.reindex(catalogue, fill_value=0)
print(zero["stock"].tolist())                # [5, 0, 12]
print(zero["stock"].dtype)                   # int64

go deeper

for a junior

Recall the three outcomes per label: kept, added with NaN, or dropped, and that the result follows the order of the list you pass.

for a middle

Explain fill_value against method, why NaN changes an int64 column's dtype, why method needs a monotonic Index, and how reindex differs from rename and set_index.

for a senior

Show the checks you run first: duplicates in the Index, label types that cannot match, and which rows the new list will silently drop.

for a principal

Argue for one agreed label set per dimension, such as the SKU catalogue or a month calendar, that pipelines reindex onto, so gaps are filled the same way everywhere.

## What reindex means in pandas To **reindex** is to conform a `Series` or `DataFrame` to a given set of labels. `products.reindex(catalogue)` returns a new frame whose Index is exactly `catalogue`, in that order. The pandas user guide calls `reindex` the fundamental data-alignment method: nearly every feature that relies on label alignment is built on it. It matches labels; it never renames them. ## What happens to each SKU | SKU is... | Result | |---|---| | in the frame and in the list | its row is kept, values unchanged | | in the list only | a new row filled with `NaN`, or with `fill_value` | | in the frame only | the row is dropped | The result follows the **list's** order, not the frame's. `DataFrame.reindex` also takes `columns=` to do the same on the column axis, and `index=` and `columns=` together conform both axes in one call. ## Filling the new rows - **`fill_value`** defaults to `np.nan`. Inserting `NaN` into a NumPy-backed `int64` or `bool` column changes its dtype (an `int64` stock count becomes `float64`). `fill_value=0` keeps `int64` because 0 fits the column. - **`method`** chooses a neighbour instead of a constant: `"ffill"` (previous label), `"bfill"` (next label) or `"nearest"`. These need an Index that is **monotonically increasing or decreasing**; otherwise pandas raises `ValueError: index must be monotonic increasing or decreasing`. - **`limit`** caps how many consecutive new labels a method fills, and **`tolerance`** caps how far an inexact match may be. - An alternative to `method` is `reindex(...)` followed by `ffill()`, which performs no order check, so use it only when the order is meaningful. ## Reading the result before trusting it A reindex that looks right can still hide surprises. Three quick checks catch most of them: - **How many rows are new?** `pd.Index(catalogue).difference(products.index)` lists the SKUs that will arrive empty. - **How many rows will vanish?** `products.index.difference(catalogue)` lists the SKUs the list leaves out. - **Did a dtype change?** Compare `products.dtypes` with the result's `dtypes`; an int column turned `float64` is the sign that new rows were filled with `NaN`. Running these before the reindex turns a silent conform into a reviewed one, which matters when the catalogue comes from another team's system. ## reindex, rename and set_index are different tools | Goal | Method | |---|---| | Keep rows whose labels are listed, add the missing ones, drop the rest | `reindex` | | Change some labels to other labels, keep every row | `rename(index={...})` | | Use a column's values as the labels | `set_index("col")` | | Replace all labels by position, one new label per row | `set_axis` | Passing a list of *new names* to `reindex` is the classic mistake: every name that is not already a label becomes a `NaN` row, and the original rows disappear. ## Building the full label list with MultiIndex.from_product The same idea fills gaps in a two-level table, such as units per store and month. `pd.MultiIndex.from_product` builds every combination, and `reindex` adds the missing ones: ```python import pandas as pd sales = pd.DataFrame({ "store": ["north", "north", "south"], "month": ["2026-01", "2026-02", "2026-01"], "units": [40, 35, 22], }).set_index(["store", "month"]) grid = pd.MultiIndex.from_product( [["north", "south"], ["2026-01", "2026-02"]], names=["store", "month"] ) full = sales.reindex(grid, fill_value=0) print(full["units"].tolist()) # [40, 35, 22, 0] ``` The south store's February row did not exist; it now does, with 0 units. When not every combination is valid, `MultiIndex.from_tuples` builds the label set from an explicit list of `(store, month)` pairs instead. ## Failure modes to recognise 1. **Duplicate labels.** If the frame's Index holds a SKU twice, `reindex` cannot know which row to use and raises `ValueError: cannot reindex on an axis with duplicate labels`. Deduplicate first. 2. **Label types that differ.** Reindexing an Index of strings onto integers, or a datetime Index onto date strings, matches nothing and returns a frame of `NaN`. 3. **Forgetting the result.** `reindex` returns a new object; the original is untouched. 4. **Silent drops.** Rows whose SKUs are missing from the catalogue vanish. Compare `products.index.difference(catalogue)` before reindexing if those rows matter.

  • Why does products.reindex(skus, method="ffill") raise on an unsorted SKU index?
    The fill methods take the value from the neighbouring label, which only has a meaning when the Index is monotonically increasing or decreasing, so pandas raises `ValueError: index must be monotonic increasing or decreasing`. Sort with `sort_index()` first, or reindex without a method and decide explicitly how to fill afterwards.
  • How does reindex_like differ from reindex in pandas?
    `a.reindex_like(b)` reindexes `a` onto `b`'s index and columns in one call, so `a` takes exactly `b`'s labels on both axes. It is still a one-sided conform: `b` is not changed. `align` instead conforms both objects to a shared set of labels and returns the pair.

  • reindex renames the existing labels to the new list in order
  • Labels missing from the new list are kept at the end of the frame
  • fill_value=0 still turns an int64 column into float64
  • reindex fills new rows with the previous row's values by default
  • reindex quietly uses the first row when a label is duplicated