Compare ZIP-area age distributions in Python
Compare genuine resident age counts and shares for fictional ZIP-coded territories, retaining uncertainty and unmatched rows.
Compare the age mix of service areas
A business is considering three ZIP-coded service areas. It wants to compare the number of young children and the shares of school-age and older residents before investigating locations, competitors and local demand. Population counts and percentages answer different parts of that question.
input.csv contains four fictional territories. The same records appear in the territories list in the Python code below. The labels and ZIP selections illustrate the join; the Census population estimates are genuine.
Save zcta_age_sex.csv below in your working directory. It is a smaller version of the paid profile: complete records for ZCTAs 01001, 10001 and 27513, with all 84 fields unchanged. The optional input CSV is already embedded in the code.
The full $29 edition includes 33,772 area profiles, 23 age bands and 46 sex/age bands per area, original source cells, uncertainty and coverage in six data tables. Postal ZIPs match the same-code Census ZCTA approximately; ZIP+4 uses five digits.
Code example
This standard-library example runs in a notebook, IPython or a script. It keeps each territory and prints population, an under-five count and age shares with approximate 90% margins of error. All displayed shares use total residents.
Paths are relative to your working folder; use from pathlib import Path; print(Path.cwd()) to check it, or supply full paths.
"""Compare resident age distributions in fictional service territories. Paste into a notebook or run as a script."""
import csv
import re
from collections import Counter
# These fictional service territories also appear in example_input.csv. They
# illustrate a ZIP join, not real customers or evidence of demand.
territories = [
{'territory': 'A', 'postal_zip': '01001'},
{'territory': 'B', 'postal_zip': '27513-1234'},
{'territory': 'C', 'postal_zip': '10001'},
{'territory': 'D', 'postal_zip': '00000'},
]
def normalize_zip(value):
if value is None or isinstance(value, str) and not value.strip():
return '', '', 'missing_input'
if not isinstance(value, str): # Never guess lost leading zeros.
return '', '', 'invalid_format'
code = value.strip()
if re.fullmatch(r'[0-9]{5}', code):
return code, 'zip5_as_supplied', ''
if re.fullmatch(r'[0-9]{9}|[0-9]{5}-[0-9]{4}', code):
return code[:5], 'zip_plus4_to_zip5', ''
return '', '', 'invalid_format'
def load_profiles(filename):
profiles = {}
with open(filename, encoding='utf-8', newline='') as source:
for row in csv.DictReader(source):
code = row['zcta_code']
if not re.fullmatch(r'[0-9]{5}', code) or code in profiles:
raise ValueError('The reference must have one row per five-digit ZCTA.')
profiles[code] = row
return profiles
def enrich_territories(input_rows, profiles):
output = []
for order in input_rows:
code, method, problem = normalize_zip(order['postal_zip'])
area = profiles.get(code)
status = problem or ('matched_zcta_code' if area is not None else 'no_zcta_match')
row = {**order, 'zip5': code, 'normalization_method': method,
'match_resolution': 'zip5' if code else '', 'match_status': status,
'matched_zcta_code': code if area is not None else ''}
for field in [name + suffix for name in ('population', 'age_under_5', 'age_under_5_pct', 'age_5_17_pct', 'age_75_plus_pct')
for suffix in ('', '_moe_90', '_status', '_moe_status')]:
row['area_' + field] = area[field] if area is not None else ''
output.append(row)
return output
profiles = load_profiles('zcta_age_sex.csv')
results = enrich_territories(territories, profiles)
assert len(results) == len(territories) # A many-to-one join must preserve input rows.
def display_share(row, metric):
stem = 'area_' + metric + '_pct'
if not row[stem]:
return row[stem + '_status']
margin = row[stem + '_moe_90']
uncertainty = f"± {float(margin):.1f} pp" if margin else row[stem + '_moe_status']
return f"{float(row[stem]):.1f}% {uncertainty}"
for row in results:
context = row['match_status']
if context == 'matched_zcta_code':
context = (f"ZCTA {row['matched_zcta_code']} | Residents {row['area_population'] or row['area_population_status']} | "
f"Under 5 {row['area_age_under_5']} ({display_share(row, 'age_under_5')}) | "
f"Ages 5–17 {display_share(row, 'age_5_17')} | "
f"Age 75+ {display_share(row, 'age_75_plus')}")
print(f"{row['territory']} | ZIP {row['postal_zip']} | {context}")
print('Input match coverage:', dict(Counter(row['match_status'] for row in results)))
# All displayed shares use total residents; the age_sex_bands.csv detail instead
# uses the matching male/female population. Approximate 90% margins are percentage
# points. Pooled period estimates describe areas, not current demand or customers.
Analysis of the output
A | ZIP 01001 | ZCTA 01001 | Residents 16234 | Under 5 862 (5.3% ± 1.3 pp) | Ages 5–17 11.9% ± 2.0 pp | Age 75+ 14.0% ± 2.2 pp
B | ZIP 27513-1234 | ZCTA 27513 | Residents 46979 | Under 5 2364 (5.0% ± 0.9 pp) | Ages 5–17 15.1% ± 1.6 pp | Age 75+ 4.4% ± 0.8 pp
C | ZIP 10001 | ZCTA 10001 | Residents 30511 | Under 5 1061 (3.5% ± 1.2 pp) | Ages 5–17 7.5% ± 2.0 pp | Age 75+ 5.1% ± 1.3 pp
D | ZIP 00000 | no_zcta_match
Input match coverage: {'matched_zcta_code': 3, 'no_zcta_match': 1}
Territories A and B have similar estimated shares of residents under five: 5.3% and 5.0%. Their estimated counts differ substantially: 862 and 2,364. Looking only at percentages would hide that difference in population size. The margins also make clear that the small difference between the percentages should not be treated as a meaningful ranking.
The estimated share age 75 or older is 14.0% in A and 4.4% in B. The share ages 5–17 is 11.9% in A and 15.1% in B. These different age mixes can help an analyst frame local research about tutoring, recreation or older-adult services. They do not tell us how many people would buy, qualify for or need a particular service.
The table describes residents, including people in group quarters. These are pooled 2020–2024 estimates, not current headcounts or forecasts. Keep uncertainty alongside the figures and assess competing services, accessibility and your own customer evidence separately.
Territory B retains its ZIP+4 and records the five-digit match. Territory D remains with no_zcta_match because 00000 is absent. The code does not guess a replacement area. Repeated customer ZIPs repeat area context; summing their population fields would double count residents.
Using the full dataset
After purchase, replace the sample with the full zcta_age_sex.csv. Replace territories with CSV records containing territory and postal_zip, importing ZIPs as text. The same code works with both reference files.
The summary includes population and male/female totals, plus seven disjoint age groups: under 5, 5–17, 18–24, 25–44, 45–64, 65–74 and 75+. Counts and shares retain uncertainty and status fields. The seven age groups partition the population; the male/female counts are a different partition of those same residents. Do not add the two sets of totals together.
age_bands.csv contains 23 age intervals per area, combining source male/female counts. Its percentages use all residents. age_sex_bands.csv contains 46 original sex/age counts per area; its percentages use the matching male or female population. Each row identifies its numerator and denominator. Filter a detail table before joining, or expect multiple rows per input.
Original age intervals have unequal widths: ages 20 and 21 each have their own category, while 85 and over is open-ended. The summary fits in Excel. The national sex/age detail and original-source table exceed Excel’s row limit; use Python or a database for those complete files.
The ZIP-area income distribution reference can add household income bands for the same ZCTA and ACS period. Those are household measures; this product counts people. Joining the area summaries does not reveal the income distribution within an age group. The household composition reference adds households with children or older adults, while the education reference adds enrollment context. These are optional separate purchases.
Sources and versions
U.S. Census Bureau, 2020–2024 ACS five-year Detailed Table B01001, released January 29, 2026. The 2024 geographic reference uses 2020 ZCTA delineations and includes Puerto Rico. ZCTAs approximate postal service areas; they are not a current USPS ZIP directory.
Age is measured in completed years at interview. The source universe is total population, including group quarters. Sex retains Census’s reported male/female categories; this is not gender-identity data. These area estimates do not identify an individual’s characteristics.
Published count margins remain available. Combined counts and percentages use documented Census uncertainty approximations, with a flagged ratio fallback where needed. Missing values and zero denominators retain explicit statuses. Sampling margins do not quantify ZIP/ZCTA mismatch.
Census sex-by-age categories · ACS definitions · Source and preparation record.
Processing improvements and genuine publisher corrections to this purchased edition are included; future source editions may be sold separately.