skip to content

In pandas, after pd.concat of twelve monthly DataFrames, why does df.loc[0] return twelve rows, and what do ignore_index and keys change?

level: seniorimportance: should knowfreq 45%

answer

  1. the original index labels survive
  2. renumber the stacked axis
  3. an outer level per source
  4. 3.0 rejects one combination

basics

~20 s

pd.concat keeps each piece's index, so twelve frames that each start at 0 stack into twelve rows labelled 0. ignore_index=True renumbers 0..n-1; keys=[...] adds an outer index level naming each month. In pandas 3.0, passing both raises ValueError.

solid answer

~40 s

`pd.concat` copies the index labels of every piece onto the stacked axis, so twelve frames read with default `RangeIndex`es produce twelve rows labelled `0`, and `df.loc[0]` returns all of them as a DataFrame. Pass `ignore_index=True` to replace the stacked axis with `0 .. n-1` when the labels carry no meaning, or `keys=["2026-01", ...]` (plus `names=["month", "row"]`) to build a `MultiIndex` whose outer level records the source, so `df.loc["2026-03"]` selects March. `verify_integrity=True` makes concat raise instead when labels repeat. In pandas 3.0, `ignore_index=True` together with `keys` raises `ValueError`, and a `keys` list whose length differs from the number of pieces raises instead of truncating. Columns are aligned by name: `join="outer"` (default) keeps all columns, `join="inner"` only shared ones.

code

python · 18 lines
python
import pandas as pd

jan = pd.DataFrame({"store": ["A", "B"], "sales": [100, 120]})
feb = pd.DataFrame({"store": ["A", "B"], "sales": [90, 130], "returns": [2, 1]})

stacked = pd.concat([jan, feb])
print(stacked.index.tolist())  # [0, 1, 0, 1]
print(len(stacked.loc[0]))  # 2 rows share the label 0

clean = pd.concat([jan, feb], ignore_index=True)
print(clean.index.tolist())  # [0, 1, 2, 3]
print(clean["returns"].dtype)  # float64: January has no returns column

tagged = pd.concat({"2026-01": jan, "2026-02": feb}, names=["month", "row"])
print(tagged.loc["2026-02"])

common = pd.concat([jan, feb], join="inner", ignore_index=True)
print(common.columns.tolist())  # ['store', 'sales']

go deeper

for a junior

Recall that concat keeps each piece's index labels and that ignore_index=True renumbers the stacked rows.

for a middle

Explain how keys and names build a MultiIndex, how columns align under join='outer' and 'inner', and why missing columns turn integers into floats.

for a senior

Diagnose label lookups returning several rows, pick between ignore_index, keys and verify_integrity, and expect the 3.0 errors when upgrading 2.x code.

for a principal

Set a convention for multi-file loads, such as a dict of frames with source keys, so provenance is never lost and schema drift is checked on every load.

## The symptom A team reads twelve monthly extracts, each into a DataFrame with a default **RangeIndex** (row labels `0, 1, 2, ...`), and stacks them with `pd.concat(frames)`. Lookups by label now behave strangely: `df.loc[0]` returns twelve rows instead of one, a later `df.loc[0, "sales"] = ...` writes to twelve rows, and a join on the index pairs rows wrongly. Nothing is broken: `concat` did exactly what it is documented to do. ## Why the labels repeat With the default `axis=0`, `pd.concat` appends rows and **keeps each piece's index labels as they are**. Twelve indexes that each run `0..n-1` give a stacked index containing every label twelve times. pandas allows **duplicate labels** in an Index, so no error is raised, and label-based selection returns every row carrying the label. Positional access with `iloc` is unaffected, which is why the problem often surfaces late. ## The three fixes, and what each means | Argument | Result index | Use when | |---|---|---| | `ignore_index=True` | new `RangeIndex` `0 .. n-1` | the old labels were just row numbers | | `keys=[...]` (with `names=`) | `MultiIndex`: source key, then original label | you need to know which piece each row came from | | `verify_integrity=True` | unchanged, but raises `ValueError` on repeated labels | the labels are meaningful ids that must stay unique | Notes on each: - `ignore_index=True` discards labels only along the concatenation axis; columns are still aligned by name. - `keys` builds a hierarchical index whose outer level holds the key for each block, so `df.loc["2026-03"]` returns March's rows. `names=["month", "row"]` names the levels, and `df.reset_index(level="month")` turns the source into an ordinary column if you prefer one. - `verify_integrity=True` checks the new axis for duplicates, which the docstring warns can be expensive relative to the concatenation itself. ## What changed in pandas 3.0 Two `concat` behaviours that used to pass silently now raise: 1. `ignore_index=True` together with `keys` raises `ValueError` ("Cannot set ignore_index=True and specify keys"). Earlier releases accepted both and quietly ignored the keys. 2. A `keys` sequence whose length differs from the number of objects raises `ValueError`. pandas 2.x truncated to the shorter of the two after a deprecation period, which could drop a whole month without a word. Both changes turn silent data loss into an error, so code written against 2.x may start failing on upgrade. The fix is to choose one of the two arguments and to build `keys` from the same list as the frames, for example from a dict: `pd.concat({"2026-01": jan, "2026-02": feb})` uses the dict keys as `keys` automatically. ## The other axis: columns While stacking rows, `concat` aligns **columns by name**: - `join="outer"` (the default) keeps the union; a column absent from one month is filled with missing values for that month's rows, which also turns an `int64` column into `float64`. - `join="inner"` keeps only columns every piece has, silently dropping a column one month introduced. A renamed column (`Sales` in one file, `sales` in the others) therefore shows up as two half-empty columns under `outer`, or disappears under `inner`. Checking `df.columns` after the stack is a cheap guard. ## Reading a keyed result With `keys`, the stacked frame's index has two levels, the source key outside and the original label inside, so every row is addressed by a pair such as `("2026-03", 0)`: - `df.loc["2026-03"]` returns March's block with its original labels; - `df.xs(0, level="row")` returns the first row of every month; - `df.index.get_level_values("month")` gives the source of each row as an array, handy for a `groupby` on provenance. Because each pair is unique as long as each piece's own labels were unique, `keys` also cures the duplicate-label symptom without throwing information away, which is why it is the better default when the files are distinct sources rather than arbitrary chunks. ## Practical habits - Build a list (or dict) of frames and call `concat` once; calling `concat` inside a loop copies the growing frame every time. - Prefer a dict with `keys` taken from the file names when provenance matters; prefer `ignore_index=True` when it does not. - With `axis=1`, `concat` places frames side by side and aligns **rows** by index label, so the same duplicate-label issue appears there as misaligned rows instead.

  • What happens in pandas 3.0 if you pass twelve frames but only eleven keys?
    `concat` raises `ValueError`. pandas 2.x truncated to the shorter sequence after a deprecation, which silently dropped the last frame. Building the input as a dict of `{key: frame}` removes the chance of a mismatch.
  • When is verify_integrity=True the right choice instead of ignore_index?
    When the index holds real identifiers, such as order ids set with `set_index`, that must stay unique across pieces. `verify_integrity=True` raises `ValueError` listing the overlapping labels, so an order exported in two monthly files is caught instead of renumbered away. It costs an extra uniqueness check over the new axis.

  • Assumes concat renumbers the index automatically when stacking rows.
  • Believes duplicate index labels are rejected by pandas.
  • Combines ignore_index=True with keys and expects the keys level to appear.
  • Uses join='inner' without noticing a column added mid-year disappears.
  • Calls concat inside a loop, one frame at a time, instead of once on a list.

Assumes pandas 3.0, where concat raises ValueError for ignore_index=True with keys and for len(keys) != len(objs); pandas 2.x ignored the keys in the first case and truncated in the second.