Compare ZIP industry counts over time in Python
Compare genuine Census employer establishment counts for fictional ZIP territories in 2019 and 2023, retaining missing observations and historical limitations.
Compare industry counts over time in your ZIP territories
A restaurant supplier wants to compare the number of full-service restaurant locations in its sales territories before the pandemic and in 2023. This guide joins postal ZIPs to Census employer establishment counts for the same six-digit industry in two years. It provides a starting point for reviewing territory coverage alongside the supplier’s own sales history.
input.csv contains four fictional territory identifiers and ZIP inputs, selected to show a leading-zero ZIP, a ZIP+4 input and a missing match. The same records appear in the territories list in the Python code below. The territory assignments are invented; the restaurant counts are genuine Census records.
Download zip_industries.csv below and save it in your working directory. This is a genuine subset of the paid file: every published six-digit industry for ZIPs 01001, 27513 and 27601 in all seven years, with all 33 fields unchanged. The code selects Full-Service Restaurants (2017 NAICS 722511) in 2019 and 2023. The input CSV is optional because its records also appear in the code.
The full $29 historical edition includes 5,229,152 ZIP–industry–year records and 245,692 ZIP-wide annual totals in nine documented CSVs. It includes the 2023 period sold in our single-year business reference; you do not need both purchases. Inspect the complete historical dataset.
Code example
Run this in a notebook, IPython or a Python script. It uses Python’s standard library and reads the CSV one row at a time, so the same code works with the full history. Change industry_code, start_year, end_year and the territory list for your comparison.
Paths are relative to your working folder; use from pathlib import Path; print(Path.cwd()) to check it, or supply full paths.
import csv
import re
from decimal import Decimal, ROUND_HALF_UP
# Fictional sales territories, also supplied in example_input.csv.
territories = [
{"territory_id": "A", "postal_zip": "01001"},
{"territory_id": "B", "postal_zip": "27513-1234"},
{"territory_id": "C", "postal_zip": "27601"},
{"territory_id": "D", "postal_zip": "00000"},
]
industry_code = "722511" # 2017 NAICS: Full-Service Restaurants
start_year, end_year = "2019", "2023"
def normalize_zip(value):
value = str(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]{5}-?[0-9]{4}", value):
return value[:5], "zip_plus4_to_zip5"
return "", "invalid_format"
def compare_territories(inputs, path, industry, before, after):
if not re.fullmatch(r"[0-9]{6}", industry):
raise ValueError("Select one six-digit 2017 NAICS industry.")
if not (2017 <= int(before) < int(after) <= 2023):
raise ValueError("Choose two ordered years within 2017–2023.")
requested = {normalize_zip(r["postal_zip"])[0] for r in inputs} - {"", "99999"}
reference = {}
with open(path, newline="", encoding="utf-8") as stream:
for row in csv.DictReader(stream):
if row["zip_code"] not in requested or row["naics_code"] != industry:
continue
if row["year"] not in {before, after}:
continue
key = (row["zip_code"], row["year"])
if key in reference:
raise ValueError("Duplicate year/ZIP/industry record.")
reference[key] = row
results = []
for entry in inputs:
zipcode, normalization = normalize_zip(entry["postal_zip"])
first, last = reference.get((zipcode, before)), reference.get((zipcode, after))
out = dict(entry, zip_code=zipcode, normalization=normalization,
naics_code=industry, start_year=before, end_year=after,
establishments_start="", establishments_end="",
net_establishment_change="", percent_change="",
source_labels_changed="", match_status="")
if normalization in {"missing_input", "invalid_format"}:
out["match_status"] = normalization
elif zipcode == "99999":
out["match_status"] = "unclassified_location_code"
else:
out["establishments_start"] = first["establishments"] if first else ""
out["establishments_end"] = last["establishments"] if last else ""
out["match_status"] = "unpublished_in_one_or_both_years"
if first and last:
a, b = int(first["establishments"]), int(last["establishments"])
out["net_establishment_change"] = str(b - a)
if a:
out["percent_change"] = str((Decimal(b-a) * 100 / a).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
labels = ("zip_name", "source_city", "source_state_abbr", "source_county_name")
out["source_labels_changed"] = str(any(first[k] != last[k] for k in labels)).lower()
out["match_status"] = "both_years_published"
results.append(out)
return results
results = compare_territories(territories, "zip_industries.csv", industry_code, start_year, end_year)
print(f"Full-service restaurant establishments, {start_year} to {end_year}")
for row in results:
if row["match_status"] == "both_years_published":
print(f"{row['territory_id']} | {row['zip_code']} | {row['establishments_start']} -> {row['establishments_end']} | net {row['net_establishment_change']} | {row['percent_change']}%")
else:
print(f"{row['territory_id']} | {row['postal_zip']} | {row['match_status']}")
Analysis of the output
Full-service restaurant establishments, 2019 to 2023
A | 01001 | 16 -> 15 | net -1 | -6.25%
B | 27513 | 40 -> 36 | net -4 | -10.00%
C | 27601 | 51 -> 49 | net -2 | -3.92%
D | 00000 | unpublished_in_one_or_both_years
ZIP 27513 had 40 published full-service restaurant establishments in 2019 and 36 in 2023, a net difference of four locations, or −10%. ZIP 27601 went from 51 to 49, a smaller proportional decline. A supplier can use those changes to put its territory sales trends in context, then investigate the places where customer activity and local establishment counts diverge.
These are counts of employer locations, not unique companies or named prospects. A net difference of four does not tell us how many restaurants opened or closed, whether the same businesses remained, or whether the ZIP’s geography changed. It is not evidence that the supplier gained or lost market share: that requires compatible customer counts, dates and industry definitions.
The ZIP+4 input is reduced to 27513; no statistics for its final four digits are estimated. The 00000 row remains with unpublished_in_one_or_both_years. A missing year or industry record is not zero. The full results list also reports whether the source’s descriptive labels changed; unchanged labels do not prove unchanged boundaries.
Using the full dataset
Extract your purchase and replace the sample with the full zip_industries.csv; the code runs unchanged. Replace territories with records read from your own CSV, retaining the territory_id and postal_zip columns or adapting their names. Select an industry from industries.csv and two years between 2017 and 2023. Preserve ZIP and NAICS codes as text.
The complete industry history exceeds Excel’s worksheet row limit. Use this streaming example or a database to select the years, ZIPs and industries you need before opening an extract in Excel. The separate ZIP-wide totals and reference tables fit within a worksheet.
zip_totals.csv provides all-industry employment, payroll and establishments for each published ZIP and year. Employment refers to the pay period including March 12; payroll is in thousands of each year’s nominal US dollars. These totals are not industry-specific and must not be allocated using establishment shares. Inflation, disclosure noise and changing business composition affect comparisons.
zip_presence.csv records which years contain a ZIP total and whether its source labels vary. It helps review coverage, but it neither harmonizes postal boundaries nor establishes when a ZIP was created or retired. The two unlocated_ tables retain the nongeographic 99999 aggregate separately.
Source N size-band cells remain blank with an explicit availability status. Withheld 2017 employment/payroll cells also remain blank; the original zero placeholders, S flags and employment-size flags are preserved in separate fields. The source stopped publishing the old employment-size flag in 2018. Missing records and source placeholders must not be treated as observed zeros.
No companion purchase is required. The 2023 snapshot is an alternative for a single-year task. For area demographics, the ZIP-area profile uses Census ZCTAs and a different survey period; equal-code postal matching remains approximate. Compare the ZIP and geography products.
Sources and versions
The original sources are the Census Bureau’s annual ZIP Business Patterns files for 2017–2023. All seven years use 2017 NAICS. The final included annual edition, 2023, was released June 26, 2025. ACD retained and prepared these files on November 28, 2026 UTC; that is not a new Census observation year.
Preparation separates detailed industries from overlapping hierarchy totals, retains disclosure states and independently checks every delivered field against the original annual files. For 2017 and 2018, descriptive ZIP labels come from the matching year’s totals file, with their separate row provenance retained. The source excludes nonemployers and its stated CBP industry exclusions.
The source and preparation record describes this fixed historical edition. Processing improvements and genuine publisher-error corrections to the purchased edition are included. Later source editions may be sold separately; this is not a subscription.
Example checked November 28, 2026 against both these samples and the complete purchased files. Source and processing records, sample checksums · Expected result CSV. Independent preparation; no agency endorsement.