---------------------------------------------------------------------- This is the API documentation for the dazdiff library. ---------------------------------------------------------------------- ## Compare Compare two tables and judge the result. diff_table(x: 'pd.DataFrame', y: 'pd.DataFrame', *, mode: 'str' = 'benchmark', by: 'Sequence[str] | str | None' = None, exclude: 'Sequence[str] | str | None' = None, row_key: 'str' = 'none', measures: 'Sequence[str] | str' = 'numeric', tolerance: 'float' = 0.0, rel_tol: 'float' = 0.0, duplicates: 'str' = 'disambiguate', cast: 'bool | None' = None, truncate: 'bool' = True) -> 'pd.DataFrame' Compare two tables value by value. Parameters ---------- x, y The tables. In ``mode="benchmark"``, ``x`` is the benchmark: ``y`` is cast to its column types and ``y``'s extra columns are dropped. In ``mode="equal"`` the tables must have the same columns with the same types. mode ``"benchmark"`` (default) or ``"equal"``. by Key columns that identify a row. Defaults to every column that is not a measure. With ``by`` given, other non-measure columns are ignored with a note in benchmark mode, and are an error in equal mode. exclude Columns, in either spelling, removed from both tables before anything else, in either mode. They need not be in both tables and are not announced as dropped or ignored. A name in neither table is a :class:`DiffWarning`; a name ``by`` or ``measures`` also names is an error. row_key ``"none"`` (default), or a virtual ``row_number`` key added to the identity: ``"position"`` numbers rows as they come, ``"sorted"`` numbers them after sorting both tables by their compared columns. Use it when every column is a measure. It cannot be combined with ``by``. measures ``"numeric"`` (float columns), ``"numeric+integer"``, or column names. tolerance, rel_tol For a finite pair, a value is ``same`` when ``abs_diff <= tolerance`` or ``rel_diff <= rel_tol``. duplicates ``"disambiguate"`` (default) pairs repeated keys in arrival order, with a warning; ``"aggregate"`` compares the multiset of values per key and measure (tolerances must be 0); ``"error"`` refuses repeated keys. cast Whether to cast the compared columns of ``y`` to ``x``'s types. ``None`` (default) casts in benchmark mode; ``False`` requires the types to agree. Equal mode never casts, so ``cast=True`` with it is an error. A number cast to text is written with the decimals ``x`` uses, when every value of ``x``'s column uses the same number of them. truncate Allow truncating non-integral values when casting to an integer column. Returns ------- pandas.DataFrame Sorted by the key. With measures (``attrs["shape"] == "cells"``), one row per key and measure, with ``metric``, ``row_id_x``, ``row_id_y``, ``value_x``, ``value_y``, ``diff``, ``abs_diff``, ``rel_diff`` and ``status``. With ``duplicates="aggregate"`` (``"groups"``), one row per key and measure, with ``n_rows_x``, ``n_rows_y``, ``values_x`` and ``values_y`` (sorted tuples). With no measures (``"rows"``), one row per source row, with ``key_seq``. ``attrs`` also holds ``mode``, ``by``, ``measures``, ``tolerance``, ``name_map``, ``dropped``, ``excluded``, ``ignored`` and ``truncated``. Raises ------ DiffError When the question cannot be answered: missing columns, type differences in equal mode, clashing names, no key, or no key in common. Warns ----- DiffWarning When the answer may be wrong: repeated keys paired by arrival order. DiffNote For expected side effects: dropped or ignored columns, truncation, no measures. is_matching(d: 'pd.DataFrame', *, tolerance: 'float | None' = None, rel_tol: 'float | None' = None) -> 'bool' ``True`` when every row of a :func:`diff_table` result is ``same``: no value changed and no row is found in only one table. Two empty tables match. With ``tolerance`` or ``rel_tol`` the values are judged again at those thresholds, looser or stricter, from the stored ``abs_diff`` and ``rel_diff``, by :func:`diff_table`'s rule: equal or both-missing values always match, and the tolerances apply to finite pairs only. When only one is given, the other is 0. A row found in only one table never matches. diff_summary(d: 'pd.DataFrame') -> 'pd.DataFrame' Condense a :func:`diff_table` result per measure. diff_explain(d: 'pd.DataFrame', column: 'str | None' = None, *, among: 'str' = 'all') -> 'pd.DataFrame' Which values of the key columns separate the rows that match from those that do not. With no ``column``, one row per key column (and per ``metric`` when the result has measures): ``column``, ``n_values``, and how many of its values are ``same_only`` (every record holding it matches), ``differ_only`` (none does) or ``mixed``. A column ``separates`` when no value is mixed; one with a different value on every record ``identifies`` and is ranked last. The others come first, fewest mixed values first, then fewest values. With a ``column`` (a key column in either spelling, or ``"metric"``), one row per value of it: ``n``, ``n_same``, ``n_changed``, ``n_only_x``, ``n_only_y`` and ``class``, most differences first. For a key column the unit is the row, which matches only when every one of its measures does; with ``duplicates="aggregate"`` it is the key; for ``metric`` it is the value. ``among="joined"`` counts only rows found in both tables, so the explanation is of the changed values alone. ## Report Draw a comparison as text. diff_report(d: 'pd.DataFrame', x_name: 'str' = 'x', y_name: 'str' = 'y', *, sample_k: 'int' = 5) -> 'DiffReport' Lay out a :func:`diff_table` result as a bounded text report. The identity and mode; the columns compared, dropped, excluded, ignored and truncated; a picture of how the rows of the two tables align; per measure that changed, its match rate and largest differences; and up to ``sample_k`` keys found in only one table. ``x_name`` and ``y_name`` label the two tables. DiffReport(x_name: 'str', y_name: 'str', mode: 'str', tolerance: 'dict', shape: 'str', unit: 'str', identity: 'list[str]', measures: 'list[str]', dropped: 'list[str]', excluded: 'list[str]', ignored: 'list[str]', truncated: 'dict', paired: 'bool', equal: 'bool', rows: 'dict', by_measure: 'pd.DataFrame | None', only_x: 'pd.DataFrame', only_y: 'pd.DataFrame', n_keys_only_x: 'int' = 0, n_keys_only_y: 'int' = 0) -> None What :func:`diff_report` found; ``str(report)`` draws it in Unicode and ``report.format(unicode=False)`` in ASCII. ## Testing Use a comparison as a test assertion. assert_table_equal(actual: 'pd.DataFrame', expected: 'pd.DataFrame', *, rel_tol: 'float' = , max_rows: 'int' = 10, **kwargs) -> 'pd.DataFrame' Assert that ``actual`` matches ``expected``, for use in tests. Runs ``diff_table(expected, actual, ...)``, with ``expected`` as the benchmark, and raises :class:`AssertionError` with :func:`diff_summary` and the first ``max_rows`` records that differ. Tables that share no key fail too. Other keyword arguments go to :func:`diff_table`. ``rel_tol`` defaults to ``sqrt(eps)`` (about 1.5e-8), as pytest and testthat compare floats, where :func:`diff_table` is exact; with ``duplicates="aggregate"``, which compares exactly, it defaults to 0. Repeated keys of rows with measures are a :class:`DiffError` unless ``duplicates`` is given: an assertion must not decide identity by arrival order. Repeated whole rows are paired, since they are identical. Returns the comparison when the tables match. ## Helpers and conditions Name normalization, and the errors, notes and warnings dazdiff raises. normalize_names(names: 'Sequence[str]') -> 'list[str]' Normalize column names as :func:`diff_table` does. Upper-case, every run of characters other than ``A-Z`` and ``0-9`` replaced by one ``_``, and ``_`` trimmed from both ends. A name that ends up empty, or two names that end up the same, are an error. DiffError The two tables cannot be compared as asked. DiffNote An expected side effect, e.g. a column was dropped or a value truncated. DiffWarning The answer may be wrong, e.g. rows were paired by arrival order. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Guide ### Get started `dazdiff` compares two tables value by value. This page walks through one comparison: a benchmark table and a stored copy of it that has drifted. ```sh pip install dazdiff ``` ## Two tables ```python import pandas as pd from dazdiff import diff_explain, diff_report, diff_summary, diff_table, is_matching benchmark = pd.read_csv("examples/benchmark.csv") stored = pd.read_csv("examples/stored.csv") ``` ``` benchmark stored id region amount units ID Region Amount Units loaded_at 1 north 100 10 1 north 100.0 10.4 2026-09-29 2 south 200 20 2 south 200.5 20.0 2026-09-29 3 east 300 30 3 east 300.0 30.0 2026-09-29 4 west 400 40 5 north 500.0 50.0 2026-09-29 ``` The headers differ in case, `stored` has an extra `loaded_at` column, its numbers are floats where the benchmark has integers, row 4 is missing and row 5 is new. ## Compare ```python d = diff_table(benchmark, stored, by=["id", "region"], measures="numeric+integer") ``` ``` DiffNote: Dropped column(s) of `y` that the benchmark `x` does not have: loaded_at. DiffNote: Truncated 2 value(s) while casting to the reference types: Amount: 1 (200.5 -> 200) Units: 1 (10.4 -> 10) ``` `diff_table()` runs in benchmark mode by default: the benchmark's columns and types are the truth. Column names are normalized, so `id` meets `ID`; the extra column is dropped; and the stored floats are cast to the benchmark's integers. Each of these is reported as a `DiffNote` warning, so nothing changes silently. `by` names the key columns, and `measures="numeric+integer"` compares the integer columns as values rather than using them as keys. The result has one row per key and measure: ```python d[d["status"] != "same"] ``` ``` ID REGION metric row_id_x row_id_y value_x value_y diff abs_diff rel_diff status 4 west AMOUNT 4 400.0 NaN NaN NaN NaN only_x 4 west UNITS 4 40.0 NaN NaN NaN NaN only_x 5 north AMOUNT 4 NaN 500.0 NaN NaN NaN only_y 5 north UNITS 4 NaN 50.0 NaN NaN NaN only_y ``` The status is `same`, `changed`, `only_x` (in the benchmark only) or `only_y` (in the tested table only). To compare the two tables as equals, without casting, use `mode="equal"`: both must then have the same columns with the same types. ## Summarize and judge ```python diff_summary(d) ``` ``` metric n n_same n_changed n_only_x n_only_y max_abs_diff mean_abs_diff rmse max_rel_diff AMOUNT 5 3 0 1 1 0.0 0.0 0.0 0.0 UNITS 5 3 0 1 1 0.0 0.0 0.0 0.0 ``` `is_matching(d)` is `True` only when every row is `same`; here it is `False`. `is_matching(d, tolerance=1)` judges the values again at another threshold without running the comparison again. `diff_table()` itself takes `tolerance` (absolute) and `rel_tol` (relative to the larger magnitude). ## Explain `diff_explain(d, "region")` counts each status per value of a column, most differences first: ``` REGION n n_same n_changed n_only_x n_only_y class 0 west 1 0 0 1 0 differ 1 north 2 1 0 0 1 mixed 2 east 1 1 0 0 0 same 3 south 1 1 0 0 0 same ``` Without a column, `diff_explain(d)` says which key columns separate the rows that match from those that do not. ## Report ```python print(diff_report(d, "benchmark", "stored")) ``` ``` ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ dazdiff report ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Identity: id, region Mode: benchmark: stored is tested against benchmark Columns ▔▔▔▔▔▔▔ Compared 4 columns: 2 keys, 2 measures. Only in stored, dropped: loaded_at. Truncated by the cast to benchmark's types: amount: 1 value (200.5 -> 200) units: 1 value (10.4 -> 10) Rows ▔▔▔▔ benchmark rows stored rows 4 (no change) 4 ┏━┯━┯━┯━┯━┓ ┃-│-│-│-│-┃ 1 only in benchmark (25.00%) ┠─┼─┼─┼─┼─┨╌╌╌┏━┯━┯━┯━┯━┓╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╮ ┃ │ │ │ │ ┃ = ┃ │ │ │ │ ┃ 3 same (100.00%) │ ┗━┷━┷━┷━┷━┛╌╌╌┠─┼─┼─┼─┼─┨╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╯ ┃+│+│+│+│+┃ 1 only in stored (25.00%) ┗━┷━┷━┷━┷━┛ Measures ▔▔▔▔▔▔▔▔ Every measure matches on every row found in both tables (2). Rows only in benchmark ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ ┌────┬────────┐ │ id │ region │ ├────┼────────┤ │ 4 │ "west" │ └────┴────────┘ Rows only in stored ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ ┌────┬─────────┐ │ id │ region │ ├────┼─────────┤ │ 5 │ "north" │ └────┴─────────┘ ``` `diff_report(d).format(unicode=False)` draws it in ASCII. ## In tests ```python from dazdiff import assert_table_equal expected = pd.DataFrame({"id": [1, 2], "amount": [100.0, 200.0]}) actual = pd.DataFrame({"id": [1, 2], "amount": [100.0, 200.0 + 1e-12]}) assert_table_equal(actual, expected) # within a relative 1.5e-8 ``` `assert_table_equal()` raises `AssertionError` with the summary and the first records that differ, so it works under pytest, unittest or a plain script. ### Command line The `dazdiff` command compares two CSV files with `diff_table()`. It is installed with the package, or on its own with `uv tool install dazdiff`; `python -m dazdiff` works too. ```sh $ dazdiff examples/benchmark.csv examples/stored.csv --by id,region --only-diffs dazdiff: Dropped column(s) of `y` that the benchmark `x` does not have: loaded_at. ID REGION metric row_id_x row_id_y value_x value_y diff abs_diff rel_diff status 1 north UNITS 1 1 10.0 10.4 0.4 0.4 0.038462 changed 2 south AMOUNT 2 2 200.0 200.5 0.5 0.5 0.002494 changed 4 west AMOUNT 4 400.0 NaN NaN NaN NaN only_x ... ``` ## Exit status `0` when the tables match, `1` when they differ, `2` on error, so `dazdiff` works in scripts and CI: ```sh dazdiff expected.csv actual.csv --by id --quiet || echo "tables differ" ``` ## Output By default the comparison is printed. `--only-diffs` keeps the rows that are not `same`, `--summary` prints the per-measure summary, `--report` draws the text report, `--explain [COLUMN]` says which key values split same from not same, and `--output FILE` writes the full comparison to a CSV file. ## CSV types CSV files carry no types, so a column read as integer in one file and as decimals in the other is compared as float; a column that is float only because of an empty value stays an integer. ## All options ``` usage: dazdiff [-h] [-b BY] [--exclude EXCLUDE] [-m MEASURES] [--mode {benchmark,equal}] [-t TOLERANCE] [-r REL_TOL] [--no-cast] [--no-truncate] [--duplicates {disambiguate,aggregate,error}] [--row-key {none,position,sorted}] [--sep SEP] [-o OUTPUT] [-s] [-R] [--x-name X_NAME] [--y-name Y_NAME] [--ascii] [-e [COLUMN]] [--joined] [-d] [-q] [--version] x y Compare two CSV files value by value. Exit status: 0 if the tables match, 1 if they differ, 2 on error. positional arguments: x first CSV file (the benchmark in benchmark mode) y second CSV file (the tested table in benchmark mode) options: -h, --help show this help message and exit -b, --by BY comma-separated key columns --exclude EXCLUDE comma-separated columns to leave out of both files -m, --measures MEASURES "numeric" (default), "numeric+integer", or comma- separated column names --mode {benchmark,equal} -t, --tolerance TOLERANCE absolute tolerance -r, --rel-tol REL_TOL relative tolerance --no-cast do not cast the second file to the first's types; they must agree --no-truncate refuse casts that would truncate values to integers --duplicates {disambiguate,aggregate,error} repeated keys: pair in arrival order (default), compare as multisets, or refuse --row-key {none,position,sorted} add a row_number key: rows as they come, or after sorting both files --sep SEP CSV field separator (default ',') -o, --output OUTPUT write the full comparison to this CSV file -s, --summary print the per-measure summary -R, --report print a text report of the comparison --x-name X_NAME the first file's name in the report (default: its file name) --y-name Y_NAME the second file's name in the report (default: its file name) --ascii draw the report in ASCII (the default when the terminal cannot show Unicode) -e, --explain [COLUMN] print which key values split same from not same; with COLUMN, per value of it --joined with --explain, count only rows found in both files -d, --only-diffs print only rows that are not 'same' -q, --quiet print nothing; use the exit status --version show program's version number and exit ```