Add ZIP-area demographics to a customer file in Python
Join fictional orders to genuine Census ZCTA population, household and income profiles using an explicitly approximate ZIP match.
Add demographic context to customer ZIPs
Your order file has postal ZIP codes, but no population or income information. The ZIP-area profile adds Census population, households, age, education and housing measures using a simple same-code ZCTA lookup. It gives you a starting point for describing the areas your business serves.
input.csv contains fictional orders, chosen to demonstrate a leading-zero code, ZIP+4 normalization and an unmatched code. The identical records appear in the orders list in the Python code below. The order amounts are invented; the Census estimates are real.
Download zcta_profile.csv below. It is a genuine subset of the paid file: complete profiles for ZCTAs 00601, 01001, 10001 and 27513, retaining all 60 fields. Save it in your working directory. The example input CSV is optional because those inputs are also in the code.
The full $29 edition contains 33,772 ZCTAs and 13 measures per area in five documented CSV tables. Inspect the full ZIP-area demographic and income dataset.
A Census ZCTA is a statistical area, not a postal delivery route. Matching the same five-digit code supplies approximate area context. It does not validate an address or establish exact postal boundaries. ZIP+4 inputs use only the first five digits.
Code example
Run this code in a notebook, IPython or a Python script. It uses Python’s standard library. ZIP codes remain text; the reference must contain one row per ZCTA, and every order remains in the result.
Paths are relative to your working folder; use from pathlib import Path; print(Path.cwd()) to check it, or supply full paths.
"""Add area context to fictional orders. Paste into a notebook or run as a script."""
import csv
import re
from collections import Counter
from decimal import Decimal
# These fictional orders also appear in example_input.csv. They illustrate a
# ZIP join; they are not real customers or evidence of demand.
orders = [
{'order_id': 'A101', 'postal_zip': '01001', 'revenue': '120.00'},
{'order_id': 'A102', 'postal_zip': '27513-1234', 'revenue': '85.00'},
{'order_id': 'A103', 'postal_zip': '10001', 'revenue': '210.00'},
{'order_id': 'A104', 'postal_zip': '00601', 'revenue': '65.00'},
{'order_id': 'A105', 'postal_zip': '00000', 'revenue': '40.00'},
]
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_orders(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 ('population', 'population_moe_90', 'population_status', 'population_moe_status',
'households', 'households_moe_90', 'households_status', 'households_moe_status',
'median_household_income', 'median_household_income_moe_90',
'median_household_income_status', 'median_household_income_moe_status',
'age_65_plus_pct', 'age_65_plus_pct_moe_90',
'age_65_plus_pct_status', 'age_65_plus_pct_moe_status'):
row['area_' + field] = area[field] if area is not None else ''
output.append(row)
return output
profiles = load_profiles('zcta_profile.csv')
results = enrich_orders(orders, profiles)
assert len(results) == len(orders) # A many-to-one join must preserve input rows.
for row in results:
context = row['match_status']
if context == 'matched_zcta_code':
income = row['area_median_household_income'] or row['area_median_household_income_status']
moe = row['area_median_household_income_moe_90'] or row['area_median_household_income_moe_status']
context = (f"ZCTA {row['matched_zcta_code']} | area households {row['area_households']} | "
f"area median household income ${income} ± {moe} (90% MOE)")
print(f"{row['order_id']} | ZIP {row['postal_zip']} | order ${row['revenue']} | {context}")
print('Input match coverage:', dict(Counter(row['match_status'] for row in results)))
print('Order revenue retained: $' + str(sum(Decimal(row['revenue']) for row in results)))
# This is same-code ZIP-area context, not a verified postal boundary match or
# an estimate of a customer's income. ZIP+4 input uses only its first five digits.
Analysis of the output
A101 | ZIP 01001 | order $120.00 | ZCTA 01001 | area households 6920 | area median household income $75342 ± 11300 (90% MOE)
A102 | ZIP 27513-1234 | order $85.00 | ZCTA 27513 | area households 19966 | area median household income $121989 ± 10465 (90% MOE)
A103 | ZIP 10001 | order $210.00 | ZCTA 10001 | area households 15737 | area median household income $129852 ± 25244 (90% MOE)
A104 | ZIP 00601 | order $65.00 | ZCTA 00601 | area households 5768 | area median household income $19454 ± 1546 (90% MOE)
A105 | ZIP 00000 | order $40.00 | no_zcta_match
Input match coverage: {'matched_zcta_code': 4, 'no_zcta_match': 1}
Order revenue retained: $520.00
Order A102 keeps its $85 order amount and original ZIP+4. Its first five digits, 27513, match a Census area with an estimated 19,966 households and median household income of $121,989. The income estimate covers the 2020–2024 period and is expressed in 2024 dollars. Its published 90% margin of error is $10,465.
The new fields let you place business activity beside the population and household context of the areas you serve. The results records also contain population, the share age 65 and over, and their uncertainty/status fields. Keep the area_ prefix: the income describes households across the ZCTA, not the buyer who placed the order. Do not interpret these fictional orders as a market study or a penetration estimate.
The 00000 input has no ZCTA match and remains in the output with its revenue. The helper separately identifies missing input and invalid format. An unmatched value alone cannot tell you whether a real postal ZIP is new, retired, PO-box-only or invalid. No nearby area is substituted.
Published margins of error reflect sampling uncertainty. They do not measure the geographic error introduced by matching a postal ZIP to a ZCTA. Avoid ranking areas from point estimates alone when the uncertainty is substantial.
Using the full dataset
Extract your purchase and replace the sample with the full zcta_profile.csv. The example runs unchanged. To use your own file, replace the fictional orders list with rows read by csv.DictReader, keeping postal_zip, order_id and revenue as text fields or adapting those names. The enrich_orders function preserves each input record. Group your own revenue by normalized ZIP separately if you want an area-level business summary; do not sum the repeated Census population or household fields after the join.
zcta_measures.csv retains each measure’s universe, units, source variables, original cells and annotations. The measure dictionary explains the 13 measures and their Puerto Rico variants. Coverage and source-accounting tables reconcile the complete source inventory. A blank analytic value is not zero; read its status. An open-ended median is not an exact point estimate.
This product needs no companion purchase. Use the postal ZIP/county crosswalk for address-based county relationships, or the tract profile when you already have compatible tract GEOIDs. Address shares are not population weights, and averaging tract medians will not produce a ZIP median. Compare the geography options.
Sources and versions
The free original source is the Census Bureau’s 2020–2024 ACS five-year Data Profiles, released January 29, 2026. ACD retained the responses, definitions and geography inventory on November 22, 2026 UTC. The 2024 geography reference uses 2020 ZCTA delineations; this is not a current USPS ZIP directory or a new November Census survey.
All 33,772 ZCTAs in the separate Census inventory are included. Puerto Rico social measures use DP02PR; the inapplicable table’s cells are verified null and accounted for. All delivered fields reconcile independently to retained original responses. No tract estimates are spatially allocated into these areas.
The source and preparation record distinguishes the Census edition from ACD processing. Processing improvements and genuine source-error corrections to this purchased edition are included. Later source editions may be sold separately; this is not a subscription.
Example checked November 22, 2026 against both these samples and the complete purchased files. Source and processing records, sample checksums · Expected result CSV. Independent preparation; no agency endorsement.