Compare ZIP-area households and families in Python

Join fictional service territories to genuine Census household composition, retaining margins of error and unmatched ZIPs.

Compare the households in your service areas

A local service business has a list of postal ZIP codes and wants to understand how its territories differ. This reference adds household composition: households containing children, older adults living alone, family and nonfamily households, and household sizes. It provides area context for market research without claiming to describe individual customers.

input.csv contains four fictional service territories. The same records appear in the territories list in the Python code below. The territory labels and ZIP selections illustrate the join; the Census figures are genuine.

Download zcta_households.csv below and save it in your working directory. This is a smaller version of the paid summary file: complete profiles for ZCTAs 01001, 10001 and 27513, with all 47 fields unchanged. The optional input CSV is also embedded in the code.

The full $29 edition covers 33,772 Census ZCTAs in five CSVs. It includes household profiles, 51 detailed categories per area, original counts and margins of error. The estimates describe 2020–2024.

Matching a postal ZIP to the identically numbered Census ZCTA supplies approximate area context. ZIP+4 inputs use only five digits. A match does not validate a postal address or establish nine-digit demographic precision.

Code example

This uses Python’s standard library and runs in a notebook, IPython or a script. It preserves the input rows and prints three household shares with 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.

Python 3.10+ · Jupyter, IPython or a script
"""Compare household composition 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 ('households_with_children_pct', 'older_adult_living_alone_pct', 'four_plus_person_households_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_households.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']} | households with under-18s {display_share(row, 'households_with_children')} | "
                   f"65+ living alone {display_share(row, 'older_adult_living_alone')} | "
                   f"4+ person households {display_share(row, 'four_plus_person_households')}")
    print(f"{row['territory']} | ZIP {row['postal_zip']} | {context}")
print('Input match coverage:', dict(Counter(row['match_status'] for row in results)))
# Each share uses all households, not people. Children, older residents and
# household-size groups overlap. MOEs are approximate 90% percentage-point
# margins. ZIP+4 uses only five digits. These area estimates do not establish
# individual customer characteristics or predict demand for a service.

Analysis of the output

A | ZIP 01001 | ZCTA 01001 | households with under-18s 22.5% ± 3.4 pp | 65+ living alone 21.3% ± 4.4 pp | 4+ person households 17.7% ± 3.6 pp
B | ZIP 27513-1234 | ZCTA 27513 | households with under-18s 30.4% ± 3.4 pp | 65+ living alone 6.6% ± 1.1 pp | 4+ person households 17.8% ± 2.2 pp
C | ZIP 10001 | ZCTA 10001 | households with under-18s 13.0% ± 2.7 pp | 65+ living alone 10.6% ± 2.1 pp | 4+ person households 5.7% ± 1.9 pp
D | ZIP 00000 | no_zcta_match
Input match coverage: {'matched_zcta_code': 3, 'no_zcta_match': 1}

Territory B retains its original ZIP+4 while matching ZCTA 27513 by its first five digits. An estimated 30.4% of households contained someone under 18, with an approximate margin of 3.4 percentage points. About 6.6% of all households consisted of one person age 65 or older, and 17.8% contained four or more people.

ZCTA 01001 has a larger estimated share of older adults living alone: 21.3% of all households, with an approximate margin of 4.4 percentage points. A service-area analyst could use that contrast to frame further research into local needs. It is not evidence that individual customers need a particular service, and this example does not test whether differences are statistically significant.

All three percentages use households, not people, as the denominator. Under-18 residents can have any relationship to the householder. The older-adult measure is the share of all households consisting of a person 65+ living alone, not the share of older adults who live alone. Household size includes everyone in the household.

These categories describe different aspects of households and are not meant to sum to 100%. More generally, a household may contain both children and older adults. Keep margins beside comparisons; sampling uncertainty does not measure postal-ZIP/ZCTA boundary differences.

Territory D remains in the results with no_zcta_match because 00000 is absent from this reference. Unavailable measures and zero household denominators are also retained as statuses rather than converted to a false zero.

Using the full dataset

After purchase, replace the sample with the full zcta_households.csv. Replace territories with records from your own CSV containing territory and postal_zip, keeping identifiers as text. Write the results list to another CSV if needed. Every input row stays present.

For more detail, use household_groups.csv. It retains the source categories with their counts, shares, margins, and parent_variable, category_depth and is_leaf fields. For example, B11005_004E identifies married-couple family households containing someone under 18. Filter to that category before joining; its percentage uses all households, not just family households.

Census family households include the householder and at least one relative. Nonfamily households include people living alone and people living with unrelated people. Parent subtotals overlap their child categories; do not add them together. Leaf rows partition the total within one source table, while the four tables overlap each other. Repeated ZIPs in a customer file repeat area context, so summing the joined household counts would double count.

The archive retains all 55 original estimate/MOE pairs per area, annotations, dictionaries, coverage and source accounting. The ZIP-area demographic profile, housing reference and commuting reference provide optional context using the same period and geography. This example requires only the household reference.

Sources and versions

Source: U.S. Census Bureau, 2020–2024 ACS five-year Detailed Tables B11001, B11005, B11007 and B11016, released January 29, 2026. The 2024 ACS geography reference uses 2020 ZCTA delineations and includes Puerto Rico.

Original Census tables · ZCTA definitions · Source and preparation record.

Published count margins are retained. Derived sums and shares use documented Census approximations, with a flagged ratio fallback where required. Same-edition processing improvements and publisher error corrections are included. Future source editions may be sold separately.