Reconcile row counts before and after a join¶
Draft: not yet validated
The code on this page was run inside MESA JupyterLab on 2026-11-13 and produced the output shown. Nobody has yet followed the steps there by hand, so a menu or a screen may differ. Tell us what you find.
A join can silently add rows, when a key repeats in the table you look things up in, or lose them, when a key has no match. Counting rows before and after catches both.
You will: have each reading joined to its gauge's name and unit, with row counts that prove the join changed nothing else.
Time: 5 to 10 minutes. You need: the notebook from
Load a file from your Data Store into a notebook, open in
MESA JupyterLab, with its first cell run so that readings
and gauges exist.
Steps¶
-
Record the size of the table you are starting from:
len(readings)You should see:
152. -
Confirm that the lookup table has one row for each key:
gauges["gauge_id"].is_uniqueYou should see:
True. If a gauge appeared twice, every one of its readings would be doubled by the join. -
Join, and have pandas enforce what you just checked:
joined = readings.merge(gauges, on="gauge_id", how="left", validate="many_to_one")You should see: no output and no error.
how="left"keeps every reading, whether or not it finds a gauge. -
Compare the sizes:
len(readings), len(joined)You should see:
(152, 152) -
Count the readings that found no gauge:
joined["name"].isna().sum()You should see:
0. Depending on the pandas version, it may be wrapped asnp.int64(0). -
Look at the result:
joined.head(3)You should see: the four original columns, then the gauge's columns.
gauge_id date value flag name unit elevation_m 0 G01 2026-07-01 0.0 NaN Boathouse mm 512 1 G01 2026-07-02 0.0 NaN Boathouse mm 512 2 G01 2026-07-03 24.9 NaN Boathouse mm 512
Check it worked¶
Three numbers agree: 152 rows before, 152 rows after, and 0 readings without a match.
Each reading now carries its unit, which you need before values from different
gauges can be compared.
If it didn't¶
MergeError: Merge keys are not unique in right dataset; not a many-to-one merge.
The lookup table has a repeated gauge_id, and validate stopped the join before it
could multiply rows. Find the repeats with
gauges[gauges["gauge_id"].duplicated(keep=False)] and settle which row is right
before you join.
Next¶
- Leave a notebook someone else can rerun
- A join carries problems along with it: rows repeated in
readingsare still repeated injoined. See Count records per day to find incomplete days. - Reference: pandas.DataFrame.merge.
Not yet validated by a person in MESA JupyterLab. Drafted with AI assistance on 2026-11-12; the code was run there on 2026-11-13 (pandas 3.1.1, DuckDB 2.0.0).
Machine-readable versions of this page: Markdown twin · raw source on GitHub · llms.txt · llms-full.txt (whole site). See For AI agents.