Skip to main content

mergeguard

Catch bad pandas merges before they silently corrupt your data.

df.merge() never complains. It will happily:

  • duplicate rows when your "lookup" table has a repeated key (revenue gets double-counted),
  • join NaN to NaN: pandas treats missing keys as equal, so unrelated rows get matched,
  • drop or blank rows because "C4" ≠ "c4 " or 42 ≠ "42",
  • explode into a cartesian product on many-to-many keys.

mergeguard tells you all of this before you merge, using only key counts, so auditing costs about as much as the merge itself, even when the merge would explode.

pip install pandas-mergeguard

Quick start

import pandas as pd
import mergeguard  # registers the df.guard accessor

orders = pd.DataFrame({
    "order_id":    [1, 2, 3, 4, 5, 6],
    "customer_id": ["C1", "C2", "C3", "c4 ", None, "C9"],
    "amount":      [120, 80, 45, 300, 15, 60],
})
customers = pd.DataFrame({
    "customer_id": ["C1", "C2", "C2", "C3", "C4", None],
    "region":      ["EU", "US", "US", "APAC", "EU", "unknown"],
})

orders.guard.audit(customers, on="customer_id", how="left")
MergeReport  how='left'  on=['customer_id']
------------------------------------------------------------
                      left   right
rows                     6   6
distinct keys            6   5
duplicated keys          0   1
null-key rows            1   1
matched rows             4   5
unmatched rows   2 (33.3%)   1 (16.7%)

relationship   1:m
output rows    7  (1.17x left rows)

Issues
  [WARN ] null_keys_match: null keys exist on both sides; pandas matches NaN to NaN, producing 1 output row(s) joined on missing keys.
  [WARN ] near_miss_keys: 1 unmatched left key(s) (1 rows) would match after normalising whitespace/case/number formatting, e.g. 'c4 ' ~ 'C4'.
  [INFO ] unmatched_left: 2 left row(s) (33.3%) have no match, e.g. 'c4 ', 'C9'.
  [INFO ] duplicate_keys_right: 1 key(s) repeat on the right (2 rows), e.g. 'C2'.
  [INFO ] unmatched_right: 1 right row(s) (16.7%) have no match, e.g. 'C4'.

Six orders would have become seven rows, and the report says exactly why. In a notebook the report renders as an HTML table.

Guarded merges in pipelines

safe_merge (or df.guard.merge) audits first and only merges if the audit passes:

enriched = orders.guard.merge(
    customers,
    on="customer_id",
    how="left",
    validate="m:1",        # each order matches at most one customer
    max_row_growth=1.0,    # a lookup join must never add rows
    min_left_match=0.95,   # at least 95% of orders must find a customer
)
mergeguard.exceptions.MergeAuditError: Merge failed audit with 1 issue(s):
  [ERROR] validate_failed: expected m:1 but right has 1 duplicated key(s), e.g. 'C2'.
  ...full report follows...
  • Errors always raise. Warnings are emitted as MergeAuditWarning; pass strict=True to make them raise as well.
  • Any other keyword (suffixes, indicator, sort ...) goes straight to pd.merge.
  • return_report=True returns (merged, report) so you can log the report.

Function-style API, if you prefer it:

from mergeguard import audit_merge, safe_merge

report = audit_merge(orders, customers, on="customer_id", how="left")
report.ok                  # False if any error-level issue
report.expected_rows       # exact output row count, computed without merging
report.left.unmatched_sample   # DataFrame of the most frequent unmatched keys
report.to_dict()           # JSON-serialisable, ready for your logs
report.raise_for_issues(strict=True)

What gets checked

Code Severity Meaning
incompatible_key_dtypes error pandas will refuse the merge (e.g. int64 vs str)
validate_failed error the validate= relationship is violated
row_growth_exceeded error output / left rows is above max_row_growth
min_left_match_failed / min_right_match_failed error too few rows find a partner
many_to_many warning key duplicated on both sides, so rows multiply
null_keys_match warning NaN keys on both sides will be joined to each other
near_miss_keys warning unmatched keys that match after trimming, case-folding, or treating "42" and 42 as the same
key_type_mismatch warning different logical types (e.g. datetime vs string)
mixed_key_types warning one key column mixes numbers and strings
all_null_key warning a key column contains only nulls
duplicate_keys_left / duplicate_keys_right info repeated keys, with examples
unmatched_left / unmatched_right info rows with no partner, with examples
null_keys info null keys on one side only
int_float_keys info integer key joined to float key
column_collision info non-key columns that will get _x / _y suffixes

validate accepts "1:1", "1:m", "m:1", "m:m" and pandas' long forms ("many_to_one" ...).

How it works

Each side is reduced to (key, count) pairs with a groupby(dropna=False). The two count tables are joined using pandas' own matching rules, including its NaN and dtype behaviour, so the predicted row count is exact. The test suite checks the prediction against real pd.merge output on hundreds of randomised frames with nulls, multi-column keys and every how.

Near-miss detection runs only on keys that are already unmatched, and only when string, mixed or mismatched key types are involved.

Limitations (v0.1)

  • Index joins (left_index=True / right_index=True) aren't supported yet; call reset_index() first.
  • how="cross" and merge_asof are out of scope.

Development

pip install -e ".[dev]"
pytest

License

MIT

Metadata

Release files for pandas-mergeguard 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pandas-mergeguard 0.1.0
File Size Uploaded Provenance Actions
pandas_mergeguard-0.1.0.tar.gz 17.5 kB With provenance Details for pandas_mergeguard-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pandas-mergeguard 0.1.0
File Interpreter ABI Platform Actions
pandas_mergeguard-0.1.0-py3-none-any.whl Python 3 none any Details for pandas_mergeguard-0.1.0-py3-none-any.whl

Total release size: 34.6 kB

Release files / pandas_mergeguard-0.1.0.tar.gz

Download URL pandas_mergeguard-0.1.0.tar.gz
Size 17.5 kB
Tags Source
SHA-256 checksum
How to use checksums
a89da9df48915734bd192bde89540d5c94b8ef35826997539093ac1e0201396c
BLAKE2b-256 checksum
How to use checksums
750115cb258c384aaf95db1d24f790a134be3ce154954e9b2b9282423c9874b7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Release files / pandas_mergeguard-0.1.0-py3-none-any.whl

Download URL pandas_mergeguard-0.1.0-py3-none-any.whl
Size 17.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6cece797c0ea692ae65800ae18abd96881cc63501ebed0ffb0752c85f2de5092
BLAKE2b-256 checksum
How to use checksums
863b4f02d4a6afb84e6119866a88a1cce470c6959166e44f2edbe5698768da57
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Security for pandas-mergeguard 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pandas_mergeguard-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page