Skip to content

pandas/merge-without-validate

Pack Severity Fix Versions
pandas warning none, edit by hand All versions

A merge duplicates rows without a warning when a key repeats on the side you expect to be unique. Prove that key unique before the join. A check of one key is far cheaper in pandas than validate=.

joined = left.merge(right, on="key", how="left")
assert right["key"].is_unique
joined = left.merge(right, on="key", how="left")

The rule reports merge without validate=, unless the lines before it prove that the join cannot repeat a row. A left join needs the right key proven unique, a right join needs the left key, and every other join needs both.

These lines prove a key unique in the frame they make or check.

  • drop_duplicates("key")
  • An aggregation of groupby("key", as_index=False)
  • A check that stops on a duplicate, such as assert df["key"].is_unique, or if df.duplicated("key").any(): followed by raise
  • A join that has validate= for that side, or whose two keys are both proven

A filter of rows, a sort, a copy and a selection of columns that keeps the key keep the proof. Anything else ends it, such as concat, a conversion or a cleanup of the key, a write into the frame, a branch, a loop, or a call that receives the frame.

The rule leaves a merge with how="cross" alone, because it pairs every row on purpose, and a merge with how="left_anti" or how="right_anti", because an anti join keeps each row of one frame at most once.

xpd has no automatic fix, so make the change by hand.

Check the side that must be unique, as in the example. When no earlier line can prove the key, pass validate= with the relation you expect, such as "many_to_one". "many_to_many" checks nothing and still scans both keys.

pandas 3.1.1 builds an index of both keys for validate=, whatever relation you name. In one measurement on 500,000 to 5,000,000 rows, validate="many_to_one" took 1.6 to 5.8 times as long as the join alone, and right["key"].is_unique took less than half as long as the join.

xpd optimize reports a validate= or a uniqueness check as redundant-key-check when an earlier line already proves the key.

This merge can silently duplicate rows. Prove the key unique first, or pass validate=.

See all rules in the pandas pack.