Compare business activity across ZIP territories in Python

Compare fictional supplier territories with genuine employer establishment counts and employee-size bands for a selected industry.

Compare the business activity in your ZIP territories

A restaurant supplier has customer locations grouped by ZIP code and wants a consistent reference for comparing territories. Census ZIP Business Patterns supplies counts of employer establishments by industry, including employee-size bands. These counts describe the business activity in an area; they do not identify individual businesses.

input.csv contains fictional territories and customer-location counts, selected to demonstrate a leading-zero ZIP, ZIP+4 normalization and an unmatched input. The identical records appear in the territories list in the Python code below. The customer counts are invented; the Census establishment counts are real.

Download zip_industries.csv below. It is a genuine subset of the paid file, containing every published six-digit industry for ZIPs 01001, 27513 and 27601 with all 31 fields. Save it in your working directory. The code selects Full-Service Restaurants, 2017 NAICS 722511. The input CSV is optional because the territory list is also in the code.

The full $29 edition contains 772,032 ZIP–industry records and 34,953 ZIP totals in eight documented reference CSVs. Inspect the complete ZIP business dataset.

Code example

Run the code in a notebook, IPython or a Python script; it uses only Python’s standard library. Selecting one industry before the join gives one reference row per ZIP. The helper keeps every input territory and treats ZIP codes as text.

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 a supplier's fictional territories with published restaurant counts."""
import csv
import re

# The optional example input CSV contains this identical fictional territory list.
territories = [
    {'territory_id': 'T01', 'postal_zip': '01001', 'active_customer_locations': '2'},
    {'territory_id': 'T02', 'postal_zip': '27513-1234', 'active_customer_locations': '5'},
    {'territory_id': 'T03', 'postal_zip': '27601', 'active_customer_locations': '4'},
    {'territory_id': 'T04', 'postal_zip': '00000', 'active_customer_locations': '0'},
]
industry_code = '722511'  # Full-Service Restaurants, 2017 NAICS.
reference_file = 'zip_industries.csv'


def normalize_zip(value):
    value = value.strip()
    if not value:
        return '', 'missing_input'
    if re.fullmatch(r'[0-9]{5}', value):
        return value, 'zip5'
    if re.fullmatch(r'[0-9]{9}|[0-9]{5}-[0-9]{4}', value):
        return value[:5], 'zip_plus4_to_zip5'
    return '', 'invalid_format'


def compare_territories(inputs, filename, naics_code):
    if not re.fullmatch(r'[0-9]{6}', naics_code):
        raise ValueError('Select one six-digit 2017 NAICS industry')
    requested = {normalize_zip(r['postal_zip'])[0] for r in inputs}
    reference = {}
    with open(filename, newline='', encoding='utf-8') as stream:
        for row in csv.DictReader(stream):
            if row['naics_code'] != naics_code or row['zip_code'] not in requested:
                continue
            if row['year'] != '2023' or row['naics_vintage'] != '2017' or row['geography_status'] != 'postal_zip' or row['zip_code'] == '99999':
                raise ValueError('Unexpected edition or nongeographic reference')
            if row['zip_code'] in reference:
                raise ValueError('Duplicate ZIP within selected industry')
            reference[row['zip_code']] = row
    results = []
    for item in inputs:
        zip5, method = normalize_zip(item['postal_zip'])
        row = reference.get(zip5)
        status = ('matched_published_industry' if row else
                  method if not zip5 else
                  'unclassified_location_code' if zip5 == '99999' else
                  'no_published_industry_match')
        results.append({**item, 'zip5': zip5, 'normalization_method': method,
                        'naics_code': naics_code, 'match_status': status,
                        'zip_name': row['zip_name'] if row else '',
                        'industry_title': row['industry_title'] if row else '',
                        'published_establishments': row['establishments'] if row else '',
                        'establishments_20_49': row['establishments_20_49'] if row else '',
                        'establishments_20_49_status': row['establishments_20_49_status'] if row else ''})
    return results


results = compare_territories(territories, reference_file, industry_code)
print('2023 full-service restaurant establishments (2017 NAICS 722511)')
print('ZIP    Customer locations*  Published establishments  With 20–49 employees')
for row in results:
    establishments = row['published_establishments'] or 'not published'
    size = row['establishments_20_49'] or 'not published'
    print(f"{row['zip5']:<6} {row['active_customer_locations']:>18}  {establishments:>24}  {size:>20}")
print('* Customer counts are fictional; Census reference counts are genuine.')

Analysis of the output

2023 full-service restaurant establishments (2017 NAICS 722511)
ZIP    Customer locations*  Published establishments  With 20–49 employees
01001                   2                        15                     4
27513                   5                        36                     7
27601                   4                        49                    23
00000                   0             not published         not published
* Customer counts are fictional; Census reference counts are genuine.

The reference reports 36 full-service restaurant establishments in ZIP 27513 in 2023; seven were in the 20–49 employee size band. ZIP 27601 has 49 establishments in the same industry, including 23 in that size band. A supplier targeting businesses of that size can compare the published local presence alongside its own customer file.

An establishment is a business location, so a company with multiple restaurants may contribute multiple establishments. These are historical employer counts, not a current list of prospects. Before calculating market penetration, establish that your customer locations use the same industry definition, time period and location-counting rules. The fictional counts here do not establish that alignment.

The ZIP+4 input is explicitly reduced to 27513; the result does not describe its last four digits. The 00000 input remains with no_published_industry_match. That status does not mean zero establishments: the code or industry may be absent from the published reference. A blank size-band value has its own availability status and is never filled with zero.

Using the full dataset

Extract your purchase and replace the sample with the full zip_industries.csv; the example runs unchanged. Replace the fictional territories list with rows from csv.DictReader, retaining the expected input column names or adapting them. Set industry_code to a six-digit code from industries.csv. The full table may contain many industries per ZIP, so keep that filter unless you intend a one-to-many result.

zip_totals.csv adds all-industry employment, payroll and establishment size counts for each published ZIP. Employment refers to the pay period including March 12; payroll is expressed in thousands of nominal 2023 dollars, with original disclosure noise flags. Those totals are not industry-specific and should not be allocated using establishment shares. The two unlocated_ files retain Census’s 99999 unclassified-location aggregate separately; it is not a geographic ZIP.

The source excludes businesses without paid employees, agricultural production and most government activity. Its unavailable size-band cells retain explicit statuses. Coverage and accounting tables explain what was retained and which overlapping industry summaries were excluded.

No companion purchase is required. The ZIP-area demographic profile can add approximate population and income context, but its Census ZCTAs and 2020–2024 survey period differ from these postal-ZIP business records. The county business reference supplies published county-level industry employment and payroll. Compare the ZIP and geography options.

Sources and versions

The free original source is the Census Bureau’s 2023 County and ZIP Business Patterns release, published June 26, 2025, using 2017 NAICS. ACD retained the ZIP totals, industry detail, classification reference and documentation on November 22, 2026 UTC. That preparation date is not a new Census observation year.

Preparation separates six-digit industries from overlapping hierarchy totals, retains source labels and original row references, and checks all eight delivered tables independently against the original files. City, state and county labels do not establish complete ZIP boundary relationships or postal validity.

The source and preparation record documents this edition. Processing improvements and genuine publisher-error corrections to your purchased edition are included. Later source editions may be sold separately; there is no 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.