Dataframes: labels, missing values and validated joins
表格数据处理
Build a pandas report that validates join cardinality, accounts for every scan and distinguishes missing measurements from zeros.
dataframesA table has identities, not just positions
A scanning log records a scan ID, a station and a page count. A second table assigns each station to a zone. We want a zone report without silently duplicating scans, losing unmatched records or turning unknown page counts into zeros.
A pandas DataFrame is a labeled two-dimensional structure whose columns can have different dtypes. Labels influence arithmetic and construction, while joins introduce relationships between tables. A plausible-looking number can be wrong because records were aligned by the wrong identity long before aggregation. The data-structures guide describes this label alignment explicitly.
Our pipeline has one reporting policy: only scans with a known station enter the zone report. Missing page counts remain among those accepted scans. Unmatched and missing station IDs go into a separate rejection table, with different reasons. No record disappears without an accounting entry.
State the schema and the relationship
Labels can align data that appear in a different order
Consider a Series with values 10 and 20 at labels a,b, and another with values 1 and 2 at labels b,a. Their sum is a:12, b:21, because pandas matches labels, not physical positions. With different label sets, alignment may introduce missing values. Converting both to unlabeled arrays would change that operation to positional arithmetic.
Use .loc for label-based selection and .iloc for positional selection. An index is not automatically a validated primary key: duplicate row labels are possible. Here scan_id is a separate, required unique column; the input index has no business meaning. The column-to-column merge ignores that index, and outputs receive fresh row positions. Label alignment, merge API
Missing, zero and false are different values
The nullable Int64 dtype holds integer page counts together with pd.NA. It is different from a plain NumPy int64 column. Zero means a measured zero-page scan; missing means the page count is unknown. The comparison pages > 0 can therefore contain true, false and unknown results. Converting pd.NA itself to a Python boolean raises an error because its truth value is ambiguous. Use .isna() to detect missingness, not == pd.NA. Missing-data semantics
If a rule requires positive known page counts, encode that policy explicitly with pages.gt(0).fillna(False). The pipeline below does not apply that filter: it keeps missing page counts in accepted jobs so the report can disclose incomplete measurement.
A left join can multiply rows
For a nonmissing key k, let m(k) be the number of matching lookup rows. In this pipeline, define m(NA)=0 for a missing scan key because lookup keys cannot be missing. A left join emits one row per match, or one unmatched row when there is no match:
If each lookup key is unique, every input scan appears exactly once after the left join. Without that constraint, a repeated station can multiply both job counts and page totals. validate='many_to_one' checks uniqueness on the right while allowing repeated stations on the left. The indicator column then identifies matched and unmatched records. Validation and match status answer different questions. Merge validation and indicator
Pandas also matches null keys to null keys, unlike the usual SQL equality-join behavior. Our lookup forbids missing station keys and missing zones, so a missing scan station cannot acquire a zone through that behavior. Missing scan stations are explicitly rejected; they are not filled with a common “unknown” key that might accidentally join.
A group report must reveal its denominator
For accepted zone g, let A_g contain its scan rows and K_g the subset with known page counts. Define job count J_g, measured count M_g and observed page subtotal T_g:
The mean is T_g/M_g when M_g is positive, otherwise missing. size() counts rows; count() counts nonmissing page values. sum(min_count=1) leaves an all-missing group missing instead of assigning it zero. The grouped-sum reference specifies this minimum-known-count condition. The subtotal is not a claim that unmeasured scans contained no pages.
Join, account for rejected rows, then aggregate
The complete example uses pandas 2.2.3 on Python 3.12. Text columns must use pandas string dtype, and pages must use nullable Int64; the function does not guess how strings or floats should be converted. Tables may be empty, but each is limited to 10,000 rows. Known page counts must lie between zero and one million. These bounds also keep every observed subtotal safely within signed 64-bit range.
Scan IDs must be present, nonempty and unique. Lookup stations and zones must be present and nonempty. Repeated lookup station keys fail merge validation, even if the duplicate would not be used by this batch. Scans may have missing or unknown station IDs. The returned accepted and rejected tables preserve scan order within their partition; the summary is sorted by zone. Unused lookup zones are not invented as zero-job groups.
import pandas as pd
def schema(frame, names, integer_columns=()):
if type(frame) is not pd.DataFrame or not frame.columns.is_unique or set(frame.columns) != set(names):
raise ValueError('unexpected or duplicate columns')
if len(frame) > 10000:
raise ValueError('teaching tables are limited to 10000 rows')
out = frame.loc[:, list(names)].copy(deep=True)
for name in names:
if name in integer_columns:
if out[name].dtype != pd.Int64Dtype():
raise ValueError('pages must use nullable Int64 dtype')
known = out[name].dropna()
if ((known < 0) | (known > 1000000)).any():
raise ValueError('known page counts must be in [0,1000000]')
elif not isinstance(out[name].dtype, pd.StringDtype):
raise ValueError('text columns must use pandas string dtype')
return out
def summarize_scans(scans, stations):
scans = schema(scans, ('scan_id', 'station', 'pages'), ('pages',))
stations = schema(stations, ('station', 'zone'))
if scans['scan_id'].isna().any() or scans['scan_id'].eq('').any() or scans['scan_id'].duplicated().any():
raise ValueError('scan IDs must be present, nonempty and unique')
for column in ('station', 'zone'):
if stations[column].isna().any() or stations[column].eq('').any():
raise ValueError('station lookup keys and zones must be present and nonempty')
joined = scans.merge(stations, on='station', how='left', sort=False,
validate='many_to_one', indicator=True)
matched = joined['_merge'].eq('both')
accepted = joined.loc[matched, ['scan_id', 'station', 'pages', 'zone']].copy()
rejected = joined.loc[~matched, ['scan_id', 'station', 'pages']].copy()
rejected['reason'] = 'unknown_station'
rejected.loc[rejected['station'].isna(), 'reason'] = 'missing_station'
groups = accepted.groupby('zone', sort=True, observed=True, dropna=False)
summary = pd.DataFrame({
'jobs': groups.size(),
'measured': groups['pages'].count(),
'observed_pages': groups['pages'].sum(min_count=1),
'mean_pages': groups['pages'].mean(),
}).reset_index()
return {'accepted': accepted.reset_index(drop=True),
'rejected': rejected.reset_index(drop=True), 'summary': summary}
def records(frame):
# Stable display only; the returned DataFrames retain nullable dtypes.
return [tuple(None if pd.isna(v) else v for v in row)
for row in frame.itertuples(index=False, name=None)]
def main():
scans = pd.DataFrame({
'scan_id': pd.array(['s1','s2','s3','s4','s5','s6','s7'], dtype='string'),
'station': pd.array(['n','n','s','s','e','gone',None], dtype='string'),
'pages': pd.array([10,None,0,6,None,8,4], dtype='Int64'),
})
stations = pd.DataFrame({
'station': pd.array(['n','s','e'], dtype='string'),
'zone': pd.array(['A','B','C'], dtype='string'),
})
result = summarize_scans(scans, stations)
print('accepted IDs:', result['accepted']['scan_id'].tolist())
print('rejected:', records(result['rejected']))
print('summary columns:', result['summary'].columns.tolist())
print('summary:', records(result['summary']))
left = pd.Series([10,20], index=['a','b'], dtype='Int64')
right = pd.Series([1,2], index=['b','a'], dtype='Int64')
print('label-aligned sum:', (left + right).to_dict())
print('positive-or-unknown:', scans['pages'].gt(0).tolist())
try:
bool(pd.NA)
except TypeError:
print('missing truth value: ambiguous')
null_left = pd.DataFrame({'key': pd.array([None], dtype='string')})
null_right = pd.DataFrame({'key': pd.array([None], dtype='string')})
print('pandas null-key matches:', len(null_left.merge(null_right, on='key')))
duplicate = pd.concat([stations, stations.iloc[:1]], ignore_index=True)
try:
summarize_scans(scans, duplicate)
except pd.errors.MergeError:
print('duplicate lookup: rejected')
if __name__ == '__main__':
main()
Output:
accepted IDs: ['s1', 's2', 's3', 's4', 's5']
rejected: [('s6', 'gone', 8, 'unknown_station'), ('s7', None, 4, 'missing_station')]
summary columns: ['zone', 'jobs', 'measured', 'observed_pages', 'mean_pages']
summary: [('A', 2, 1, 10, 10.0), ('B', 2, 2, 6, 3.0), ('C', 1, 0, None, None)]
label-aligned sum: {'a': 12, 'b': 21}
positive-or-unknown: [True, <NA>, False, True, <NA>, True, True]
missing truth value: ambiguous
pandas null-key matches: 1
duplicate lookup: rejected
Zone A has two jobs but only one known measurement. Its observed subtotal and measured mean are both ten; the unmeasured job has not been assigned zero pages. Zone B includes a real zero and a six, giving subtotal six and mean three. Zone C has one job and no known measurements, so both its subtotal and mean remain missing.
The summary constructor combines Series indexed by zone. Pandas aligns them by that label before reset_index makes zone a regular column. This is useful alignment, unlike silently adding two unrelated Series just because they have the same length. The records helper replaces missing markers with None only for stable display; returned DataFrames retain their nullable dtypes.
The two rejection reasons are mutually exclusive, and every input row belongs to exactly one output partition. Consequently the accepted row count equals the sum of reported job counts, and accepted plus rejected equals the input count. These are useful audit invariants. They do not prove that the station directory was correct or current.
For n scan rows, k lookup rows and g reported zones, the validated relationship keeps the joined result linear in n. A conventional hash-join/grouping cost model gives expected O(n+k+g*log(g)) work including sorted groups, with linear-sized intermediate tables. This is an algorithmic model under hashing and fixed-size-value assumptions, not a pandas API latency guarantee. String hashing, dtype choices, allocation and implementation details affect real costs. Without the relationship constraint, the join’s output alone can grow quadratically for heavily duplicated keys.
Correct arithmetic can still summarize the wrong population
The mean reports only measured accepted scans. It does not estimate all scans without additional assumptions about missing measurements and rejected stations. Discarding rejected rows without reporting them would hide that selection. Filling unknown page counts with zero would answer a different question.
The lookup has no effective dates. A station that changed zones over time would require a time-aware relationship rather than this static key match. Scan ID uniqueness is also a stated application rule; another dataset might intentionally contain several events for one scan and need a compound key. Avoid “fixing” unexpected duplicates with drop_duplicates() until their meaning is understood.
The function copies its inputs and uses explicit .loc assignments on its owned tables. It does not depend on a chained assignment modifying some earlier view. It also does not define a general ownership guarantee for arbitrary nested object columns; those are excluded by the schema. Moving to another pandas version requires checking the actual dtype and copying contracts used there.
This is an in-memory batch report, not a database transaction or a live monitor. Parsing files, reconciling station names, choosing imputation, and preventing train/test leakage in downstream model features remain separate decisions. A clean DataFrame is not evidence that those decisions were correct.
Audit the rows before interpreting the summary
- Predict label alignment. Series L has
a:10,b:20; Series R storesb:1,a:2. What is L+R? Why not 11 and 22?
Match labels, not positions
Answer: The result is a:12,b:21. Pandas adds values with the same label despite their different storage order. Positional array addition would instead pair the first values and the second values, which is a different operation.
- Catch a duplicated lookup key. Two scan rows reference station n, and the lookup accidentally contains two rows for n. How many matched rows would an unchecked join emit? What happens here?
Apply the relationship constraint
Answer: It would emit four matched rows: each scan pairs with both lookup records. Here validate='many_to_one' raises MergeError instead. A merge indicator alone would mark all four as matched and would not reveal that the relationship was invalid.
- Distinguish unmeasured from zero. A zone has two accepted jobs with page counts
[0, NA]. Give its job count, measured count, observed subtotal and measured mean. Then consider[NA, NA].
Keep the denominator visible
Answer: For [0,NA], the values are 2, 1, 0 and 0. For [NA,NA], they are 2, 0, missing and missing. min_count=1 prevents an all-missing subtotal from appearing as a measured zero.
- Check null join keys. Why does the program reject null station keys in the lookup instead of assuming they never match null scan keys?
Use pandas semantics explicitly
Answer: Pandas matches null join keys to one another. A null lookup key could therefore assign a zone to an unidentified station. Rejecting null lookup keys and classifying missing scan keys separately implements the intended policy instead of relying on SQL-style intuition.
Labeled computation and relational checks complement each other
The pandas guides on data structures, merging and missing data describe three different contracts: how labels align values, how keys form row pairs, and how unknown values propagate. A reliable table workflow states all three. Grouped aggregates then need a declared denominator and missing-value policy.
Compare this workflow with NumPy arrays, whose arithmetic is primarily positional, and data structures, where key identity and multiplicity also matter. Before turning a table into model inputs, verify row identity, feature order, lookup timing and which records contributed to each statistic. Those checks often matter more than shortening the method chain.
Make a prediction, then check
A zone has page counts [0, NA]. What are jobs, measured, observed subtotal and measured mean?
Learning objectives
- Identify when labels rather than positions determine a table operation.
- Validate a many-to-one relationship and account for matched, unknown and missing keys.
- Report measured denominators and distinguish missing subtotals from measured zeros.
Prerequisites & connections
Explore related knowledge →References
- Intro to data structures — pandas 2.2.3 documentation
pandas development team - pandas.merge — pandas 2.2.3 documentation
pandas development team - Working with missing data — pandas 2.2.3 documentation
pandas development team - SeriesGroupBy.sum — pandas 2.2.3 documentation
pandas development team
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Eight tests pass with actual CPython 3.12.4 and pandas 2.2.3 in the project .venv. A pure Python record/dictionary reference with Fraction means checks every returned row and summary field across 24 seeded batches plus eight missing/zero/empty/shared-zone cases; it does not use pandas merge or groupby.
- Checked partition conservation, output schemas and selected nullable dtypes, arbitrary duplicate input indexes, input preservation after output mutations, lookup and scan reorder behavior, duplicate right keys including unused keys, null-to-null library joins versus pipeline rejection, schema/value limits, and a 10,000-row subtotal of 10^10. Nine stdout lines are extracted from and match both articles.
- Complete bilingual prose, identical code, two display formulas, six anchors and four answers pass strict MDX/KaTeX plus actual React HTML/MathML inspection. Fixed mixed multiline math delimiters before freezing. All test paths are controlled by article_text. Written is AI author checking, not human review. No whole-site build, global install or performance measurement was performed.
- Independent AI review requested an explicit definition for missing scan keys in the join-size formula: m(NA)=0 under this pipeline’s nonmissing lookup-key rule. Both languages now state it; code and tests are unchanged. Eight tests and strict rendering pass again.
- Ran all eight author tests under project CPython 3.12.4 and pandas 2.2.3. Independently represented scan-to-lookup and lookup-to-zone relations as integer incidence matrices M and Z; G=MZ determines accepted rows, while G-transpose times known masks and page vectors gives counts and subtotals. Six targeted datasets produce 23 returned rows across complete accepted/rejected/summary comparisons, avoiding the author record/dictionary aggregation reference.
- Independent cases include repeated input indexes, two stations sharing a zone, Unicode zone sorting, missing and empty station strings, zero versus missing measurements, empty lookup/cohort, and unused lookup entries. With copy-on-write explicitly set both False and True, mutations of all three returned tables leave both input tables unchanged. Reviewed many_to_one checks on unused duplicates and the SQL-null contrast from the author tests.
- Full bilingual review found one incomplete formula definition: m(k) was defined only for nonmissing keys although the sum ranges over all scan rows. The author added m(NA)=0 under this pipeline non-null lookup contract in both languages and recorded the AI clarification in metadata. Re-read the revised sentences and final five hashes; code and tests remain unchanged. No remaining defect was identified.
- Verified partition conservation, measured denominator, min_count=1, signed-64 subtotal bound, static-lookup limitation, fixed-size/hash-model cost qualification and ownership exclusions. Strict MDX/KaTeX and actual React HTML pass with two matching displays, six anchors and four answers per language; author tests confirm identical code and nine stdout lines. Source IDs/URLs match metadata exactly and all five SHA values match the final frozen manifest. No author or repository file was edited by this reviewer.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Intro to data structures — pandas 2.2.3 documentation · Actually read Series label alignment and union with missing values at lines 280–322; heterogeneous DataFrame and constructor alignment at 349–368, plus label selection and iloc discussion.
- pandas.merge — pandas 2.2.3 documentation · Actually read column joins ignoring indexes, null-key matching warning, left-order preservation, indicator and many_to_one right-key uniqueness at lines 61–139. Also read the 2.2.3 user_guide/merging.html validation/indicator section at 635–672. No SQL-equivalent null claim.
- Working with missing data — pandas 2.2.3 documentation · Actually read nullable Int64 and isna at 72–105, comparison versus NA at 122–205, and ambiguous scalar truth value at 257–270. Reading distinguishes missing, zero and false, with explicit dtype and filtering policy.
- SeriesGroupBy.sum — pandas 2.2.3 documentation · The exact /version/2.2.3/ API request failed with Internal Error. The /version/2.2/ URL successfully returned documentation labeled pandas 2.2.3; actually read min_count at 142–160: insufficient nonmissing values produce NA. No reliance on unrelated engine text.
- Intro to data structures — pandas 2.2.3 documentation · Actually read fixed pandas 2.2.3 data-structures guide lines 280–322 for label-aligned Series arithmetic and missing values from index union. Reviewed the article distinction between application scan_id and arbitrary duplicate DataFrame row labels. No positional arithmetic equivalence is claimed.
- pandas.merge — pandas 2.2.3 documentation · Actually read fixed 2.2.3 merge API lines 61–91 for column joins ignoring indexes, null-null warning and left-order preservation, and 119–139 for copying, indicator and many_to_one uniqueness. Also read the linked official 2.2.3 merging guide lines 579–651 for pre-merge key validation versus match indicators. All scoped library behavior was actually exercised with pandas 2.2.3.
- Working with missing data — pandas 2.2.3 documentation · Actually read fixed 2.2.3 missing-data guide lines 87–104 for isna, 122–171 for equality and nullable Int64, and 217–270 for logical propagation and ambiguous bool(NA). Verified that this pipeline retains unknown page counts while rejecting missing lookup keys; no general missing-at-random or unbiased population estimate is inferred.
- SeriesGroupBy.sum — pandas 2.2.3 documentation · Actually opened the exact metadata /version/2.2/ groupby sum URL, whose title identifies pandas 2.2.3. Read lines 142–160 for signature and minimum nonmissing count; did not rely on unrelated engine prose. Empty-group versus all-missing-group distinctions are explicit in the article and tested.
Related topics