Compare ZIP-area education and enrollment in Python
Compare genuine attainment and enrollment estimates for fictional ZIP-coded territories, retaining population definitions, uncertainty and unmatched rows.
Compare education and school enrollment across ZIP areas
An education-services business has a list of ZIP-coded territories. It wants to compare adult educational attainment and the resident student population before deciding where to investigate a new program. This reference adds those area characteristics, with separate measures for completed education and current school enrollment.
input.csv contains four fictional territories. The same records appear in the territories list in the Python code below. The territory labels and ZIP selections demonstrate the join; the Census estimates are genuine.
Save zcta_education.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 72 fields unchanged. The optional input CSV is already embedded in the code.
The full $29 edition includes 33,772 ZCTA profiles, attainment by age and sex, enrollment by level and public/private type, original source cells, uncertainty and coverage in eight data tables.
Postal ZIPs match the same-code Census ZCTA as an approximation. ZIP+4 uses five digits; a match does not validate an address or provide nine-digit estimates.
Code example
The example runs in a notebook, IPython or a script using Python’s standard library. It keeps every input row and prints three shares with approximate 90% margins of error. Each label identifies its population: adults age 25 and older, all residents age three and older, or enrolled K–12 students.
Paths are relative to your working folder; use from pathlib import Path; print(Path.cwd()) to check it, or supply full paths.
"""Compare education and enrollment 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 ('some_college_no_degree_pct', 'k12_enrolled_pct', 'private_k12_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_education.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']} | Some college, no degree (age 25+) {display_share(row, 'some_college_no_degree')} | "
f"K–12 students (residents age 3+) {display_share(row, 'k12_enrolled')} | "
f"Private/home school (K–12 students) {display_share(row, 'private_k12')}")
print(f"{row['territory']} | ZIP {row['postal_zip']} | {context}")
print('Input match coverage:', dict(Counter(row['match_status'] for row in results)))
# Shares use three distinct denominators: residents age 25+, all residents
# age 3+, and K–12 students. Approximate 90% margins are percentage points.
# These pooled five-year estimates describe area residents, not individual
# customers, school locations, training interest or service demand.
Analysis of the output
A | ZIP 01001 | ZCTA 01001 | Some college, no degree (age 25+) 19.3% ± 3.2 pp | K–12 students (residents age 3+) 11.6% ± 2.1 pp | Private/home school (K–12 students) 4.4% ± 3.8 pp
B | ZIP 27513-1234 | ZCTA 27513 | Some college, no degree (age 25+) 14.3% ± 2.2 pp | K–12 students (residents age 3+) 14.9% ± 1.6 pp | Private/home school (K–12 students) 11.9% ± 3.0 pp
C | ZIP 10001 | ZCTA 10001 | Some college, no degree (age 25+) 10.6% ± 2.1 pp | K–12 students (residents age 3+) 7.4% ± 1.8 pp | Private/home school (K–12 students) 31.5% ± 6.2 pp
D | ZIP 00000 | no_zcta_match
Input match coverage: {'matched_zcta_code': 3, 'no_zcta_match': 1}
Territory B has a higher point estimate for K–12 students as a share of residents age three and older than Territory C: 14.9% versus 7.4%. Among those K–12 students, C has a higher share in Census’s private-school category: 31.5% versus 11.9%. The two measures answer different questions: how prominent K–12 enrollment is in the resident population, and how enrolled students are divided between public and private education.
Census includes home schooling in the private-school category. These estimates describe where students live, not where their schools are located. They do not measure available school places, school quality, enrollment growth or likely customers. An analyst can use the comparison to choose questions for local market research and then add the business’s own information about services and customers.
The adult measure adds another perspective: 19.3% of Territory A’s adults age 25 and older have some college education but no degree, compared with 14.3% in B and 10.6% in C. That describes completed education; it does not establish interest in returning to school. Keep the margins beside the estimates. This example does not test statistical significance or rank the territories as business opportunities.
Territory B retains its original ZIP+4 and records its five-digit match. Territory D remains with no_zcta_match because 00000 is absent from the reference. Missing estimates and zero denominators retain explicit statuses. Sampling margins do not quantify ZIP/ZCTA boundary mismatch.
Using the full dataset
After purchase, replace the sample with the full zcta_education.csv. Replace territories with records from your CSV containing territory and postal_zip, importing ZIPs as text. The same code works with both reference files.
The profile contains five counts and eleven prepared shares with uncertainty and status fields. Overall attainment uses adults age 25 and older. The detail file attainment_by_age.csv also covers ages 18–24 and separates five age groups by sex; each percentage uses that specific age/sex population.
enrollment_by_level.csv separates preschool, kindergarten, individual grades and undergraduate/graduate enrollment, with percentages among all enrolled residents age three and older. enrollment_by_type.csv separates public/private enrollment within sex and school-level groups. Filter the detail categories before joining these files, which contain multiple rows per area. The K–12 share in the profile is not an attendance rate among school-age children.
The ZIP workforce reference adds resident occupations and employment; it does not locate jobs. The internet-access reference adds household connectivity, which can help frame questions about online delivery. Both use the same ACS period and ZCTA geography, with different population denominators, and remain optional separate purchases. Repeated customer ZIPs repeat area counts, so do not sum joined counts as distinct residents.
Sources and versions
U.S. Census Bureau, 2020–2024 ACS five-year Detailed Tables B15003, B15001, B14007 and B14002, released January 29, 2026. These are pooled five-year estimates, not a 2024 point-in-time count or a cumulative five-year enrollment total. The 2024 geographic reference uses 2020 ZCTA delineations and includes Puerto Rico.
School enrollment refers to attendance at any time in the three months before interview. It covers schooling that advances a person toward a diploma or degree; non-degree vocational training and on-the-job training are excluded. Attainment is the highest completed level or degree, not the level currently attended.
Educational attainment · Attainment by age and sex · Enrollment by level · Public/private enrollment · Source and preparation record.
Published count margins remain available. Combined counts and percentages use documented Census uncertainty approximations. Processing improvements and genuine publisher corrections to this purchased edition are included; future source editions may be sold separately.