In pandas, after pd.concat stacks two monthly product extracts, how do you detect duplicate index labels, and how do you stop them arising?
answer
- each piece keeps its labels
- a cached uniqueness check
- keep=False marks every copy
- a flag that refuses repeats
basics
~10 sCheck df.index.is_unique and list repeats with df.index.duplicated(keep=False). Prevent them with ignore_index=True on the concat, or guard a frame with set_flags(allows_duplicate_labels=False), which raises DuplicateLabelError when a repeat appears.
solid answer
~40 s`pd.concat` keeps each input's labels, so two extracts that each carry a `RangeIndex` produce the labels 0, 1, ... twice. pandas allows repeated labels by default, so nothing fails until a method that needs unique labels runs; `reindex`, for one, raises `ValueError: cannot reindex on an axis with duplicate labels`. Detect them with `df.index.is_unique` or `has_duplicates`, and list them with `df.index[df.index.duplicated(keep=False)]`. Fix them at the source: `ignore_index=True` on the concat when the labels mean nothing, or deduplicate on the key. To guard a pipeline, `df.set_flags(allows_duplicate_labels=False)` makes an operation that introduces a repeat raise `DuplicateLabelError`; the user guide marks this flag experimental. In pandas 3.0, `set_index(verify_integrity=True)` is deprecated; check `result.index.is_unique` instead.
code
python · 21 linesimport pandas as pd
jan = pd.DataFrame({"sku": ["A-100", "B-300"], "units": [4, 7]})
feb = pd.DataFrame({"sku": ["A-100", "C-500"], "units": [2, 9]})
both = pd.concat([jan, feb])
print(both.index.tolist()) # [0, 1, 0, 1]
print(both.index.is_unique) # False
print(both.index.duplicated().tolist()) # [False, False, True, True]
try:
both.reindex([0, 1, 2])
except ValueError as err:
print(err) # cannot reindex on an axis with duplicate labels
try:
both.set_flags(allows_duplicate_labels=False)
except pd.errors.DuplicateLabelError:
print("flag refused the repeated labels")
print(pd.concat([jan, feb], ignore_index=True).index.is_unique) # Truego deeper
Recall that a pandas Index may repeat labels, that concat keeps each piece's labels, and that index.is_unique tells you whether repeats exist.
Explain duplicated's keep options, why reindex raises on repeats, and the choice between ignore_index=True and deduplicating on the real key.
Show where you put the uniqueness check in a pipeline, why the experimental flag is a tripwire rather than a guarantee, and how 3.0's verify_integrity deprecation changes existing code.
Weigh failing fast on repeated keys at ingestion against tolerating and resolving them later, and who owns the rule for which copy wins.
## Why pandas allows duplicate labels at all A pandas **Index** is not required to be unique. That surprises people who think of row labels as a primary key, but pandas is often the tool that *cleans* messy data, and raw data has repeats even in fields meant to be unique. So pandas accepts duplicate labels by default and leaves detection and prevention to you. The general idea that nothing enforces a row key's uniqueness belongs to the library-neutral material on row labels; this answer is about the pandas tools. ## Where duplicates come from - **`pd.concat` of pieces with their own default index.** Each monthly extract has a `RangeIndex` 0..n-1; stacking two of them repeats every label. - **`set_index` on a key column that has repeats.** A SKU sold twice in an extract becomes a repeated label. - **`rename` that maps two labels to the same new label.** - **Reading raw files** with an index column that was never unique. ## What breaks, and what silently changes | Operation | With duplicate labels | |---|---| | `reindex`, `reindex_like` | raises `ValueError: cannot reindex on an axis with duplicate labels` | | arithmetic with a differently labelled object | pairs every copy with every copy, multiplying rows | | a lookup of one label | returns several rows where one was expected | | `set_flags(allows_duplicate_labels=False)` | raises `DuplicateLabelError` | The raising cases are the lucky ones. The silent ones change row counts downstream. ## Detecting them - **`df.index.is_unique`**: `True` or `False`. The check costs a pass over a large index, but pandas caches the result. - **`df.index.has_duplicates`**: the negation, often easier to read in an `assert`. - **`df.index.duplicated(keep=...)`**: a boolean array. `keep="first"` (the default) marks every copy after the first, `keep="last"` every copy before the last, and `keep=False` marks **all** copies, which is what you want to inspect them. - **`df.index.value_counts()`**: shows how many times each label repeats. ## Preventing them 1. **Renumber when the labels mean nothing.** `pd.concat(pieces, ignore_index=True)`, or `reset_index(drop=True)` afterwards, gives a fresh `RangeIndex`. The concat's own `verify_integrity=True` raises `ValueError: Indexes have overlapping values` instead, when overlap is a bug. 2. **Deduplicate on the real key** before making it the Index, deciding explicitly which copy wins. 3. **Check after `set_index`.** In pandas 3.0, `set_index(..., verify_integrity=True)` is deprecated and emits a `Pandas4Warning`; the documented replacement is to check `result.index.is_unique` yourself. 4. **Make a frame refuse repeats.** `df.set_flags(allows_duplicate_labels=False)` returns a frame flagged against duplicates. Setting the flag on a frame that already has repeats raises `DuplicateLabelError`, and so does an operation that would introduce one, such as a `rename` onto an existing label. The flag is "sticky" across operations that propagate it, but the user guide marks it **experimental**: many methods do not propagate it yet, so treat it as a tripwire, not a guarantee. ## Row numbers or a real key? The two prevention routes answer different questions, and mixing them up is a common source of bugs: - **Positional row numbers** (the default `RangeIndex`) carry no meaning. Repeats there are an artefact of stacking, and `ignore_index=True` is the whole fix. - **A business key** (SKU, order id, month) carries meaning. Renumbering hides the repeat without resolving it: two rows for A-100 are still two rows. Decide which copy wins, or aggregate, before the key becomes the Index. - **A composite key** may be unique where its parts are not. `set_index(["sku", "month"])` builds a `MultiIndex` whose pairs can be unique even though each SKU repeats across months; check `is_unique` on the combined Index. ## A guard for a pipeline ```python import pandas as pd jan = pd.DataFrame({"sku": ["A-100", "B-300"], "units": [4, 7]}) feb = pd.DataFrame({"sku": ["A-100", "C-500"], "units": [2, 9]}) stacked = pd.concat([jan, feb], ignore_index=True) by_sku = stacked.set_index("sku") if not by_sku.index.is_unique: repeats = by_sku.index[by_sku.index.duplicated(keep=False)].unique().tolist() print("repeated SKUs:", repeats) # repeated SKUs: ['A-100'] ``` Here the row numbers are clean after `ignore_index=True`, but the SKU key is not: A-100 appears in both months. Whether to sum, keep the latest or reject the batch is a business decision; the pandas part is making sure the repeat is noticed before an alignment multiplies it.
- What does df.index.duplicated() mark with its default keep, and when do you pass keep=False?The default `keep="first"` marks every occurrence after the first as `True`, which suits dropping repeats with `df[~df.index.duplicated()]`. `keep=False` marks every occurrence, including the first, which is what you want when inspecting the conflicting rows side by side before deciding which one wins.
- Why is set_flags(allows_duplicate_labels=False) not enough on its own to guarantee unique labels?The pandas user guide marks the flag experimental: many methods do not yet propagate it to their result, so a frame produced further down a pipeline can lose the flag and accept repeats again. Use it as an early tripwire and keep an explicit `index.is_unique` check at the boundaries that matter.
- pandas refuses to create an Index with repeated labels
- pd.concat renumbers the rows of the result by default
- df.index.duplicated() marks every copy of a repeated label
- set_index(verify_integrity=True) is still the recommended check in pandas 3.0
- allows_duplicate_labels=False is guaranteed to survive every later method
Assumes pandas 3.0, which deprecates set_index's verify_integrity keyword (Pandas4Warning) in favour of checking index.is_unique; pandas 2.x accepted it without a warning.