Fix Pandas Reindex Duplicate Labels Error in OHLCV Data
A pandas reindex duplicate labels error means the index repeats a timestamp, so pandas cannot map each label to one row position. Find the repeats with index.duplicated(keep=False), classify them, then dedupe with the right rule.
- Reindex, align(), assignment and concat axis=1 raise this error when an index repeats, but join does not raise and silently multiplies rows, so find out which object holds the duplicates first.
- Classify duplicates before deleting: identical rows, revised bars, and legitimate repeats (ticks, multi-symbol) need different fixes.
- df.drop_duplicates() ignores the index, so use df[~df.index.duplicated(keep='last')] or groupby(level=0).agg for OHLCV.
- Sort the index before using keep='first' or keep='last', because keep depends on row order.
- Stop recurrence by asserting index.is_unique at ingestion, using merge(validate=...) and concat(verify_integrity=True), and quarantining dropped rows.
Why does pandas raise the reindex duplicate labels error?
The reindex duplicate labels error, whose full text is "cannot reindex on an axis with duplicate labels", appears because reindexing means "give me the rows for these labels". pandas builds a map from label to integer position. If a label appears twice, the map has two answers for one label, and pandas refuses to guess.
The error is a data-quality signal. In market data it nearly always means two bars or ticks share a timestamp, usually after merging vendor files or appending overlapping downloads.
The same check runs behind several operations, so the traceback may point at a line that does not look like a reindex. One operation behaves differently: df.join does not raise this error. It expands rows instead, which is harder to notice.
| Operation | Where the duplicate matters |
|---|---|
| df.reindex(new_index) | Duplicates in the source df.index (duplicates in the target alone are allowed) |
| df['x'] = series | Assignment aligns series to df.index; fails if the series index is duplicated and differs from df.index |
| df.align(other) / reindex-based alignment | Duplicates in either index when the indexes are not identical raise the error |
| df.join(other) | Does not raise this error. If the other index repeats a label, matching rows are multiplied (many-to-many), so the result silently grows |
| df.loc[list_of_labels] | Fine on its own in recent pandas, but later alignment steps fail |
| pd.concat([a, b], axis=1) | Duplicates in any index when the indexes differ |
| resample / asfreq after a reindex | Inherit the error from an earlier step |
import pandas as pd
idx = pd.to_datetime(["2024-01-02 09:30", "2024-01-02 09:31", "2024-01-02 09:31"])
a = pd.DataFrame({"close": [10.0, 10.1, 10.2]}, index=idx)
full = pd.date_range("2024-01-02 09:30", periods=4, freq="min")
a.reindex(full)
# ValueError: cannot reindex on an axis with duplicate labels
s = pd.Series([1, 2], index=pd.to_datetime(["2024-01-02 09:30", "2024-01-02 09:30"]))
a["x"] = s
# same ValueError, because s has a duplicated indexHow do I find which timestamps are duplicated?
Start by checking which object holds the duplicates. With align or assignment, check both sides, since the traceback does not say which one. With join there is no traceback at all, so check the other side before joining.
Use keep=False so every member of a duplicate group is flagged, not only the later copies.
- Test uniqueness on every object involved: a.index.is_unique and b.index.is_unique.
- Count the damage: a.index.duplicated().sum() for surplus rows, and a.index.value_counts().loc[lambda s: s > 1] for per-timestamp counts.
- Print all members of each group: a[a.index.duplicated(keep=False)].sort_index().
- Check the index dtype. Mixed tz-aware and naive values, or float timestamps, can look equal but fail to match.
dups = a[a.index.duplicated(keep=False)].sort_index()
print(dups)
# exact copies vs conflicting values
exact = a.duplicated(keep=False) & a.index.duplicated(keep=False)
print("exact duplicate rows:", exact.sum())
# which timestamps have differing values
conflict = (a[a.index.duplicated(keep=False)]
.groupby(level=0).nunique().gt(1).any(axis=1))
print(conflict[conflict].index) Which kind of duplicate do I have before deleting anything?
Deleting is only safe once you know why the repeat exists. Three cases look identical in the traceback but need different handling.
Exact duplicates are the same timestamp with identical values, typically from overlapping files. Any keep rule is safe.
Conflicting duplicates share a timestamp but differ in values. This is a vendor revision, a partial bar versus a final bar, or two vendors disagreeing. Which row wins is a data-provenance decision.
Legitimate repeats are ticks or trades in the same millisecond, or a frame holding several symbols under one DatetimeIndex. Deduping these destroys real data.
| Data type | Duplicate cause | Correct rule |
|---|---|---|
| OHLCV, identical rows | Overlapping files | keep='first' or 'last', equivalent |
| OHLCV, revised values | Newer download corrects older | Sort by file date, keep='last' |
| OHLCV, primary vs backup vendor | Two sources | keep='first' with the primary source placed first |
| OHLCV split into partial bars | Sub-bars aggregated to one timestamp | groupby(level=0).agg with first/max/min/last/sum |
| Ticks or trades | Same-timestamp events | Keep all; add a sequence number or use a MultiIndex |
| Multi-symbol frame | Shared DatetimeIndex | MultiIndex (symbol, timestamp) or pivot |
| tz-naive local times | DST fall-back hour repeats | Localize with tz and ambiguous handling, convert to UTC |
How do I remove duplicate timestamps and keep the last or first?
df.drop_duplicates() compares column values only and ignores the index. Two rows with different timestamps but equal prices are dropped, while two rows with the same timestamp and different prices are kept. It is the wrong tool for this error.
Use the index mask instead. keep='first' retains the first occurrence in current row order, and keep='last' the final one, so sort or order the data deliberately first.
For concatenated vendor files, build the frame in chronological file order (oldest download first), then keep='last' so corrections win. Use a stable sort so file order survives within equal timestamps.
# files ordered oldest -> newest download
parts = [pd.read_parquet(p) for p in sorted(paths)]
df = pd.concat(parts)
# stable sort keeps file order inside equal timestamps
df = df.sort_index(kind="stable")
df = df[~df.index.duplicated(keep="last")]
# alternative using a column, safe against index-ignoring drop_duplicates
df = (df.reset_index()
.drop_duplicates(subset=["timestamp"], keep="last")
.set_index("timestamp"))
# partial bars that must be combined, not discarded
agg = df.groupby(level=0).agg(
open=("open", "first"), high=("high", "max"),
low=("low", "min"), close=("close", "last"),
volume=("volume", "sum"))What are the common sources of duplicate labels in market data?
Overlapping vendor files and incremental downloads are the most frequent: each pull re-fetches the last day or bar, so appending produces repeats at the seams.
DST fall-back is subtler. With tz-naive local times, 01:00 to 02:00 occurs twice on the transition day. Localize to the exchange timezone, then convert to UTC, and store UTC.
Rounding or flooring timestamps to bars collapses distinct times into one label, for example 09:30:00.4 and 09:30:00.9 both floor to 09:30:00.
Merging or joining on non-unique keys multiplies rows. If both sides hold two rows for a key, the result has four. Catch it with validate on merge, because join will not warn you, and a later reindex then fails far from the cause.
Float or NaN timestamps are another trap. A float epoch value compared to a datetime index never matches, and NaT values repeat as duplicate labels.
# DST: localize, then convert
idx = pd.to_datetime(raw["time"]) # naive local
idx = idx.dt.tz_localize("America/New_York", ambiguous="infer")
raw.index = idx.dt.tz_convert("UTC")
# fail early instead of exploding rows
merged = left.merge(right, on="timestamp", validate="one_to_one")
stacked = pd.concat([a, b], verify_integrity=True) # raises on duplicate labels
# multi-symbol: unique MultiIndex
m = df.set_index(["symbol", "timestamp"]).sort_index()
assert m.index.is_unique
wide_close = m["close"].unstack("symbol")What if the duplicates must stay, and how do I prevent them in a pipeline?
For ticks, align without reindex. Reset the index and use pd.merge_asof, which needs sorted keys but allows repeated ones, or groupby per timestamp and then reindex the result.
For bar data, dedupe first, then reindex against a full trading calendar so missing bars show as NaN and can be audited separately.
Prevention belongs at the ingestion boundary, so a reindex duplicate labels failure never reaches research code. Normalize to UTC, sort, assert uniqueness, and write idempotent upserts keyed by (symbol, timestamp), for example one Parquet partition per symbol and date that is rewritten whole. Log how many rows were dropped and save them to a quarantine file.
Common mistakes: keeping first when the latest file holds corrections, silently dropping real ticks, deduping after resampling instead of before, and suppressing the error with a try/except instead of finding the cause.
import pandas as pd
def validate_ohlcv(df, quarantine_path=None, keep="last"):
"""Return a clean OHLCV frame or raise. Index must be DatetimeIndex."""
if not isinstance(df.index, pd.DatetimeIndex):
raise TypeError(f"index is {type(df.index).__name__}, expected DatetimeIndex")
if df.index.tz is None:
raise ValueError("index is tz-naive; localize and convert to UTC")
if df.index.hasnans:
raise ValueError("index contains NaT")
before = len(df)
df = df.sort_index(kind="stable")
dup_mask = df.index.duplicated(keep=False)
if dup_mask.any():
grp = df[dup_mask]
conflict = grp.groupby(level=0).nunique().gt(1).any(axis=1)
if conflict.any():
raise ValueError(
f"{conflict.sum()} timestamps have conflicting duplicates, e.g. "
f"{list(conflict[conflict].index[:5])}")
if quarantine_path:
grp.to_parquet(quarantine_path)
df = df[~df.index.duplicated(keep=keep)]
assert df.index.is_unique and df.index.is_monotonic_increasing
bad = (df["high"] < df[["open", "close"]].max(axis=1)) | \
(df["low"] > df[["open", "close"]].min(axis=1))
if bad.any():
raise ValueError(f"{bad.sum()} bars violate high/low bounds")
print(f"rows before={before} after={len(df)} dropped={before - len(df)}")
return dfCommon questions
What is the difference between keep='first' and keep='last' in index.duplicated?
keep='first' marks every repeat after the first occurrence as duplicated, so the first row survives. keep='last' marks all but the final occurrence, so the last row survives. Both depend on current row order, so sort first.
Why does the error appear even though my target index has no duplicates?
reindex requires the source index to be unique. Duplicates in the object being reindexed trigger the error regardless of the target. For assignment and align(), the other object's index must be unique too, unless the indexes are identical.
Why did my join return more rows without any error?
DataFrame.join does not raise the duplicate labels error. When the other frame's index repeats a label, each matching left row is multiplied (many-to-many). Check other.index.is_unique before joining, or use merge with validate='one_to_one' or 'many_to_one'.
Can I reindex a frame with duplicates using a MultiIndex?
Yes, if the combination of levels such as (symbol, timestamp) is unique. Check with m.index.is_unique after sort_index. The timestamp level alone may still repeat across symbols, which is fine.
Should I dedupe tick data?
Usually not. Distinct trades can share a timestamp at the vendor's resolution, so dropping them loses volume. Add a sequence number or exchange sequence ID and index by (timestamp, seq), or use merge_asof for alignment.