Compare ZIP-area rents and housing-cost burdens in Python
Join fictional service territories to genuine Census rent and renter/owner housing burdens, retaining uncertainty and unmatched ZIPs.
Compare housing costs across service areas
A housing analyst or local service planner has a list of postal ZIP codes and wants to compare rent and housing-cost burdens across those areas. This reference supplies Census ZCTA estimates for renters and homeowners, with the counts, denominators and uncertainty needed to interpret them.
input.csv contains four fictional service territories. The same records appear in the territories list in the Python code below. The territory names and ZIP selections are illustrative; all housing estimates come from the actual product.
Download zcta_housing.csv below and save it in your working directory. It is a smaller version of the paid summary file: complete profiles for ZCTAs 01001, 10001 and 27513, with all 67 fields unchanged. The optional input CSV is also embedded in the code.
The full $29 edition covers 33,772 ZCTAs in six CSVs. It includes median gross rent, renter and owner burdens, mortgage subgroups and income-band detail. These are 2020–2024 ACS five-year estimates, not current asking rents.
Matching a postal ZIP to the identically numbered Census ZCTA supplies approximate area context. ZIP+4 is reduced to five digits. The match does not establish identical postal boundaries or an individual household’s financial circumstances.
Code example
This uses Python’s standard library and runs in a notebook, IPython or a script. It keeps identifiers as text, preserves unmatched territories and prints renter and owner shares spending at least 30% of income on housing. Margins are approximate 90% margins of error in percentage points.
Paths are relative to your working folder; use from pathlib import Path; print(Path.cwd()) to check it, or supply full paths.
"""Compare housing costs 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 input.csv above. 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 ('median_gross_rent', 'median_gross_rent_status',
'renter_burdened_30plus_pct', 'renter_burdened_30plus_pct_moe_90',
'renter_burdened_30plus_pct_status', 'renter_burdened_30plus_pct_moe_status',
'owner_burdened_30plus_pct', 'owner_burdened_30plus_pct_moe_90',
'owner_burdened_30plus_pct_status', 'owner_burdened_30plus_pct_moe_status'):
row['area_' + field] = area[field] if area is not None else ''
output.append(row)
return output
profiles = load_profiles('zcta_housing.csv')
results = enrich_territories(territories, profiles)
assert len(results) == len(territories) # A many-to-one join must preserve input rows.
def display_share(row, tenure):
stem = 'area_' + tenure + '_burdened_30plus_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':
rent = row['area_median_gross_rent'] or row['area_median_gross_rent_status']
context = (f"ZCTA {row['matched_zcta_code']} | median gross rent ${rent} | "
f"renter burden {display_share(row, 'renter')} | "
f"owner burden {display_share(row, 'owner')}")
print(f"{row['territory']} | ZIP {row['postal_zip']} | {context}")
print('Input match coverage:', dict(Counter(row['match_status'] for row in results)))
# Shares use units with computed cost/income ratios; margins are approximate
# 90% percentage-point MOEs. ZIP+4 uses only five digits. Area estimates do not
# establish an individual's finances or an exact postal boundary match.
Analysis of the output
A | ZIP 01001 | ZCTA 01001 | median gross rent $1318 | renter burden 33.7% ± 11.1 pp | owner burden 26.8% ± 4.9 pp
B | ZIP 27513-1234 | ZCTA 27513 | median gross rent $1617 | renter burden 38.8% ± 6.4 pp | owner burden 15.6% ± 3.0 pp
C | ZIP 10001 | ZCTA 10001 | median gross rent $3361 | renter burden 40.3% ± 3.7 pp | owner burden 14.5% ± 4.4 pp
D | ZIP 00000 | no_zcta_match
Input match coverage: {'matched_zcta_code': 3, 'no_zcta_match': 1}
Territory B’s original ZIP+4 remains in the result. Its first five digits match ZCTA 27513, where median monthly gross rent was $1,617. Among renter-occupied units with a computed cost-to-income ratio, 38.8% spent at least 30% of household income on housing. The corresponding homeowner share was 15.6%.
Those measures help describe housing-cost pressure in each territory. They can accompany a service-area comparison alongside household counts or income context. They do not show which customers are burdened or predict demand.
The renter estimate for ZCTA 01001 has an approximate margin of 11.1 percentage points. Keep that uncertainty beside comparisons; the example does not establish that the areas differ statistically. Census sampling uncertainty also does not measure postal-ZIP/ZCTA mismatch.
The percentages exclude cases for which Census did not compute a ratio. The full summary keeps eligible and not-computed counts separately. Missing or zero-denominator results remain flagged; they are not zero burden. Territory D remains unmatched because 00000 is absent from this reference.
Using the full dataset
After purchase, replace the sample with the full zcta_housing.csv. Replace territories with your own CSV records containing territory and postal_zip; retain ZIP values as text. The results list is ready to write to another CSV, and every input row is preserved.
The summary also supplies severe burden at the 50%-of-income threshold. Use cost_burden.csv for owners with and without mortgages, and income_burden.csv for five positive-income groups by tenure. Income-group detail supplies 30%-plus burdens; it does not invent a 50%-plus breakdown.
Filter a cohort or income group before joining detail tables. Owner totals overlap mortgage subgroups, and 50%-plus counts are part of 30%-plus counts. Do not add overlapping categories or average area percentages and medians. Field definitions, all 81 source estimate/MOE pairs per area, annotations, coverage and source accounting accompany the download.
The ZIP-area demographic profile is an optional separate purchase for population and basic income context. The housing guide works independently.
Sources and versions
Source: U.S. Census Bureau, 2020–2024 ACS five-year Detailed Tables B25064, B25070, B25091 and B25106, released January 29, 2026. Dollar measures use 2024 inflation-adjusted dollars. The 2024 ACS geography reference uses 2020 ZCTA delineations and includes Puerto Rico.
Original Census tables · ZCTA definitions · Source and preparation record.
Published margins are retained; derived sums and shares use documented Census approximations. Same-edition processing improvements and publisher error corrections are included. Future source editions may be sold separately.