Compare ZIP-area housing stock in Python

Compare genuine housing age, structure and vacancy estimates for fictional ZIP-coded territories, retaining uncertainty and unmatched rows.

Compare housing across service territories

A home-service business or housing analyst has a list of postal ZIP codes and wants to compare the housing in those areas. This reference adds housing types, construction periods and occupancy measures to the territory file.

input.csv contains four fictional service territories. The identical 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_housing_stock.csv below in your working directory. This is a smaller version of the paid profile: complete records for ZCTAs 01001, 10001 and 27513, with all 67 fields unchanged. The optional input CSV is already embedded in the code.

The full $29 edition provides 33,772 ZCTA profiles and detailed occupancy, vacancy, structure, construction-period and tenure tables, with original counts, margins and coverage in nine data tables.

Matching a postal ZIP to the same-code Census ZCTA provides approximate area context. ZIP+4 uses five digits. A match does not validate an address or provide nine-digit estimates.

Code example

This uses Python’s standard library and runs in a notebook, IPython or a script. It keeps every input row and prints the shares of housing units in detached structures, built before 1980 and vacant, with approximate 90% margins of error.

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 housing stock 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 ('detached_units_pct', 'pre1980_units_pct', 'vacant_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_housing_stock.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']} | Detached units {display_share(row, 'detached_units')} | "
                   f"built before 1980 {display_share(row, 'pre1980_units')} | "
                   f"vacant units {display_share(row, 'vacant')}")
    print(f"{row['territory']} | ZIP {row['postal_zip']} | {context}")
print('Input match coverage:', dict(Counter(row['match_status'] for row in results)))

# These shares use all housing units, not buildings. MOEs are approximate
# 90% margins in percentage points. ZIP+4 uses five digits. Housing age does not
# establish repair needs; vacant units include seasonal and other categories.

Analysis of the output

A | ZIP 01001 | ZCTA 01001 | Detached units 56.6% ± 3.8 pp | built before 1980 74.7% ± 7.1 pp | vacant units 3.1% ± 2.1 pp
B | ZIP 27513-1234 | ZCTA 27513 | Detached units 57.6% ± 2.6 pp | built before 1980 7.8% ± 1.9 pp | vacant units 6.2% ± 1.8 pp
C | ZIP 10001 | ZCTA 10001 | Detached units 1.0% ± 0.8 pp | built before 1980 53.0% ± 4.1 pp | vacant units 14.3% ± 3.0 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 units in detached homes: 56.6% and 57.6%. Their construction-period profiles differ: about 74.7% of units in A were originally built before 1980, compared with 7.8% in B. This adds useful context to a territory comparison even when its broad housing mix looks similar.

A home-service business could use that difference to decide what to investigate locally. Construction age alone does not identify homes needing repairs, recent renovations or likely customers. These are area estimates for 2020–2024, not property records.

Territory C has about 1.0% of units in detached structures and a 14.3% vacant share. The latter includes seasonal housing and other vacancy categories; it is neither the rental vacancy rate nor a count of currently available listings. Use vacancy_status.csv to examine the composition of vacant units.

All three displayed shares use all housing units as their denominator. The figures count units, not buildings: one 20-unit building contributes 20 units. Keep uncertainty beside comparisons; the example does not test statistical significance.

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 values and zero denominators retain explicit statuses. Sampling margins do not quantify the ZIP/ZCTA boundary mismatch.

Using the full dataset

After purchase, replace the sample with the full zcta_housing_stock.csv. Replace territories with your own CSV records containing territory and postal_zip, importing ZIPs as text. The same code works with both files.

The summary provides five counts and ten shares, each with its margin and status. Detailed files retain occupied/vacant counts, seven vacancy categories, ten structure types, ten construction periods, and structure types within owner- and renter-occupied units.

Filter detail categories before joining: they have multiple records per area. Vacancy-category shares use vacant units; tenure-by-structure shares use the named owner or renter population. Separate construction-period and tenure tables do not identify the age of owner-occupied housing. Repeated customer ZIPs repeat area counts, so do not sum joined counts as distinct housing units.

The ZIP housing-cost reference adds affordability and cost burdens, while the ZIP demographic reference adds income and population context. Both are optional separate purchases from the same ACS period; this guide needs only the housing-stock reference.

Sources and versions

U.S. Census Bureau, 2020–2024 ACS five-year Detailed Tables B25002, B25004, B25024, B25032 and B25034, released January 29, 2026. The 2024 ACS geographic reference uses 2020 ZCTA delineations and includes Puerto Rico.

Units in structure · Year built · Vacancy status · 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.