Metadata-Version: 2.5
Name: pandas-mergeguard
Version: 0.1.0
Summary: Catch bad pandas merges before they silently corrupt your data: row explosions, unmatched keys, NaN-to-NaN joins and near-miss keys.
Project-URL: Homepage, https://github.com/AnmolAdhikari/mergeguard
Project-URL: Issues, https://github.com/AnmolAdhikari/mergeguard/issues
Project-URL: Changelog, https://github.com/AnmolAdhikari/mergeguard/blob/main/CHANGELOG.md
Author-email: Anmol Adhikari <anmoladhikari03@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: data-engineering,data-quality,join,merge,pandas,validation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: numpy>=1.23
Requires-Dist: pandas>=2.0
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Description-Content-Type: text/markdown

# 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.

```bash
pip install pandas-mergeguard
```

## Quick start

```python
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:

```python
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:

```python
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

```bash
pip install -e ".[dev]"
pytest
```

## License

MIT
