Compare ZIP-area income distributions in Python

Compare genuine household income and poverty estimates for fictional ZIP-coded territories, retaining uncertainty, distinct populations and unmatched rows.

Compare household income distributions across ZIP areas

A business has a list of ZIP-coded service territories. It wants to understand how household incomes are distributed before researching prices and services in each area. A median gives one point in the distribution; income bands show how many households fall below or above a chosen amount.

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

Save zcta_income_distribution.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 area profiles, 16 household-income bands and seven income-to-poverty bands per area, original source cells, uncertainty and coverage in six data tables. Postal ZIPs match the same-code Census ZCTA approximately; ZIP+4 uses five digits.

Code example

This standard-library example runs in a notebook, IPython or a script. It preserves each territory and prints income and poverty shares with approximate 90% margins of error. Income shares use households; poverty shares use people for whom poverty status is determined.

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 income distribution and poverty 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_under_50000_pct', 'households_50000_99999_pct', 'households_100000_plus_pct', 'people_below_poverty_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_income_distribution.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 under $50k {display_share(row, 'households_under_50000')} | "
                   f"$50k–$99,999 {display_share(row, 'households_50000_99999')} | "
                   f"$100k+ {display_share(row, 'households_100000_plus')} | "
                   f"People below poverty {display_share(row, 'people_below_poverty')}")
    print(f"{row['territory']} | ZIP {row['postal_zip']} | {context}")
print('Input match coverage:', dict(Counter(row['match_status'] for row in results)))

# Income shares use households; poverty shares use people whose poverty status
# Census determines. Approximate 90% margins are percentage points.
# Pooled five-year estimates describe areas, not individual customers or demand.

Analysis of the output

A | ZIP 01001 | ZCTA 01001 | Households under $50k 32.4% ± 6.3 pp | $50k–$99,999 27.0% ± 4.4 pp | $100k+ 40.5% ± 5.7 pp | People below poverty 6.2% ± 2.0 pp
B | ZIP 27513-1234 | ZCTA 27513 | Households under $50k 14.5% ± 2.5 pp | $50k–$99,999 25.5% ± 3.1 pp | $100k+ 60.0% ± 3.9 pp | People below poverty 5.1% ± 1.9 pp
C | ZIP 10001 | ZCTA 10001 | Households under $50k 23.6% ± 3.8 pp | $50k–$99,999 18.8% ± 3.6 pp | $100k+ 57.7% ± 4.3 pp | People below poverty 15.1% ± 2.4 pp
D | ZIP 00000 | no_zcta_match
Input match coverage: {'matched_zcta_code': 3, 'no_zcta_match': 1}

About 60.0% of households in Territory B have income of $100,000 or more, compared with 40.5% in A. Households below $50,000 account for 14.5% in B and 32.4% in A. These are different income mixes that a business can consider alongside its own prices, customers and local research; they do not establish willingness to buy.

Territory C illustrates why it helps to retain more than one measure. Its estimated share of households at $100,000 or more is 57.7%, while its estimated poverty rate is 15.1%, compared with 5.1% in B. The poverty rate counts people, not households, and compares family or individual income with the applicable poverty threshold. It is not the share of households earning below a fixed dollar amount.

Keep the margins beside the estimates. This example compares point estimates without testing statistical significance or ranking business opportunities. The estimates describe areas, not the income or eligibility of a particular customer. Repeating an area for multiple customers does not create additional households or residents.

Territory B retains its ZIP+4 and records the five-digit match. Territory D remains with no_zcta_match because 00000 is absent. Missing estimates and zero denominators retain explicit statuses; sampling margins do not quantify postal ZIP/ZCTA boundary mismatch.

Using the full dataset

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

The profile has nine counts and seven shares with uncertainty and statuses. household_income_bands.csv preserves all 16 original income categories, from below $10,000 through $200,000 or more, in 2024 inflation-adjusted dollars. The lowest band includes zero and negative incomes. poverty_ratio_bands.csv preserves seven categories, from below half the poverty threshold through at least twice the threshold. Filter categories before joining detail tables: each has multiple rows per ZCTA.

The profile's below-$50,000, $50,000–$99,999 and $100,000-plus groups partition households. The $200,000-plus group is a subset of $100,000-plus. Likewise, people below 200% of poverty include those below 100%. Do not add overlapping groups as if they were separate populations.

The ZIP demographic reference adds population and median income from the same ACS period. The housing-cost reference adds rent and ownership-cost burdens. The IRS ZIP income reference describes tax returns and adjusted gross income for a different source period and geography; its income groups are not interchangeable with ACS households. These are optional separate purchases.

Sources and versions

U.S. Census Bureau, 2020–2024 ACS five-year Detailed Tables B19001 and C17002, released January 29, 2026. These are pooled five-year estimates, not 2024 point-in-time counts. The 2024 geographic reference uses 2020 ZCTA delineations and includes Puerto Rico.

Household income combines the householder's income with that of other household members age 15 and older, related or unrelated. It covers money income before taxes during the past 12 months; it excludes capital gains and noncash benefits. Dollar amounts are adjusted to 2024. Poverty thresholds account for family size and composition and do not vary geographically. The poverty universe excludes institutionalized people, people in military group quarters or college dormitories, and unrelated children under 15.

Household income categories · Income-to-poverty categories · Source and preparation record.

Published count margins remain available. Combined counts and shares use documented Census uncertainty approximations. Processing improvements and genuine publisher corrections to this purchased edition are included; future source editions may be sold separately.