Territory design looks like a mapping problem and is really a graph problem: split a set of areas into k groups that are contiguous, roughly equal on some workload measure, and not absurdly shaped. US teams usually want to do it with ZIP codes. ZIP codes are not polygons, so the first job is to understand the polygons you actually have.
Everything below ran on 24 November 2026 against real data: 57 ZCTAs around Austin, Texas, with their 2020 Census populations, split into four territories.
ZCTA vs ZIP code
A ZIP Code is a USPS delivery attribute: a set of addresses and delivery points, some of them a single building or a bank of PO boxes. The Census Bureau builds ZIP Code Tabulation Areas (ZCTAs) as generalized polygons for those codes, assembled from census tabulation blocks. From the Bureau’s ZCTA methodology:
- Each block with housing units goes to the ZIP Code used by most addresses in that block. Every inhabited area has a ZCTA.
- Every 2020 ZCTA code was a valid USPS ZIP Code on 1 January 2020, but not every ZIP Code has a ZCTA. PO-box-only and single-organisation ZIPs often have none.
- ZCTAs can be noncontiguous (islands, enclaves), and uninhabited land or water over two square miles may belong to no ZCTA.
- They are delineated for each decennial census. USPS changes ZIP Codes continuously; ZCTAs do not follow.
So “ZCTA to ZIP code” is a crosswalk problem, not a rename. For mailing lists or CRM records keyed by ZIP, the HUD-USPS ZIP crosswalk files map ZIPs to tracts and counties quarterly; for ZIP to ZCTA, the most common case is that the codes match, and the exceptions are exactly the PO-box and unique ZIPs above, which you assign to the ZCTA that contains them.
Getting boundaries and population
Three sources, depending on what you need:
- Cartographic boundary files (
cb_2020_us_zcta520_500k.zip) are generalized and light, the right choice for maps and territory work. - TIGER/Line ZCTA shapefiles are full resolution, for precise spatial joins.
- TIGERweb is a query service. Its 2020 Census ZCTA layer carries
POP100andHU100(2020 population and housing units), so one request gets shapes and counts together. That is what we used:
curl -G "https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/PUMA_TAD_TAZ_UGA_ZCTA/MapServer/7/query" \
--data-urlencode "geometry=-97.95,30.15,-97.55,30.5" \
--data-urlencode "geometryType=esriGeometryEnvelope" \
--data-urlencode "inSR=4326" \
--data-urlencode "spatialRel=esriSpatialRelIntersects" \
--data-urlencode "outFields=ZCTA5,GEOID,POP100,HU100,AREALAND" \
--data-urlencode "outSR=4326" \
--data-urlencode "f=geojson" -o zcta.geojsonThat returned 57 ZCTAs (2.4 MB of GeoJSON) with a combined 2020 population of 1,791,623. For current estimates or other measures (households, income, business counts) use the American Community Survey 5-year tables by ZCTA, for example total population B01003_001E or households B11001_001E.
The problem, stated precisely
Partition the ZCTAs into k territories so that:
- Contiguous: each territory is one connected piece, under queen contiguity (sharing any boundary point counts as adjacent).
- Balanced: the largest deviation from the mean workload is small. We used population; use whatever drives the work.
- Compact: no territory is a long snake. We score shape with Polsby–Popper, 4π·area / perimeter², which is 1 for a circle and near 0 for a thin strip.
Exact solutions are expensive: this is a constrained graph-partitioning problem. Two practical routes exist. The library route is spopt, PySAL’s regionalisation package, which implements max-p regions, SKATER, AZP and related methods. The do-it-yourself route, below, is a hundred lines you can read in one sitting and tune for your own constraints.
A simple algorithm that works
- Seed k territories far apart: start from the most populous ZCTA, then repeatedly add the ZCTA farthest from all chosen seeds.
- Grow: the territory with the lowest load claims the unassigned neighbour that shares the most borders with it. Repeat until everything is assigned. Contiguity holds by construction.
- Swap: look at every ZCTA on a territory boundary and try moving it to each neighbouring territory. Keep the single best move that lowers
deviation + λ · (1 − worst Polsby–Popper)and does not disconnect the territory it leaves. Repeat until no move helps.
import math
import geopandas as gpd
import networkx as nx
from libpysal.graph import Graph
K = 4 # number of territories
LAMBDA = 0.25 # weight of the compactness penalty; 0 = balance only
gdf = gpd.read_file("zcta.geojson").to_crs(5070) # CONUS Albers: equal-area, metres
gdf = gdf.set_index("ZCTA5").sort_index()
pop = gdf["POP100"].astype(int).to_dict()
# Queen contiguity: ZCTAs that share any boundary point are neighbours.
g = Graph.build_contiguity(gdf, rook=False)
G = nx.Graph()
G.add_nodes_from(gdf.index)
G.add_edges_from((a, b) for a, b in g.adjacency.index if a != b)
assert nx.is_connected(G), "split islands into their own problem first"
target = sum(pop.values()) / K
def seeds(k):
# Farthest-point seeding on centroids spreads the seeds across the study area.
c = gdf.geometry.centroid
chosen = [max(pop, key=pop.get)]
while len(chosen) < k:
chosen.append(max(gdf.index, key=lambda z: min(c[z].distance(c[s]) for s in chosen)))
return chosen
def grow(seed_list):
# Region growing: the lightest territory claims its best-connected unassigned neighbour.
assign = {s: i for i, s in enumerate(seed_list)}
load = [pop[s] for s in seed_list]
while len(assign) < len(G):
for t in sorted(range(K), key=lambda t: load[t]):
frontier = {n for z, tt in assign.items() if tt == t for n in G[z] if n not in assign}
if frontier:
pick = max(frontier, key=lambda n: (sum(assign.get(m) == t for m in G[n]), -pop[n]))
assign[pick] = t
load[t] += pop[pick]
break
else:
raise RuntimeError("unreachable ZCTAs")
return assign
def loads(assign):
out = [0] * K
for z, t in assign.items():
out[t] += pop[z]
return out
def deviation(assign):
return max(abs(l - target) for l in loads(assign)) / target
def polsby_popper(assign, t):
shape = gdf.loc[[z for z, tt in assign.items() if tt == t]].geometry.union_all()
return 4 * math.pi * shape.area / shape.length ** 2
def cost(assign):
worst_shape = min(polsby_popper(assign, t) for t in range(K))
return deviation(assign) + LAMBDA * (1 - worst_shape)
def contiguous_without(assign, z):
rest = [n for n, t in assign.items() if t == assign[z] and n != z]
return bool(rest) and nx.is_connected(G.subgraph(rest))
def swap(assign, max_rounds=500):
# Local search: move one boundary ZCTA to a neighbouring territory when that lowers
# the cost and leaves its old territory contiguous. Stop when no move helps.
for _ in range(max_rounds):
best, move = cost(assign), None
for z, t in assign.items():
for u in {assign[n] for n in G[z]} - {t}:
if not contiguous_without(assign, z):
continue
assign[z] = u
c = cost(assign)
assign[z] = t
if c < best:
best, move = c, (z, u)
if not move:
return assign
assign[move[0]] = move[1]
return assign
def report(label, assign):
l = loads(assign)
print(f"{label}: loads={l} max/min={max(l) / min(l):.3f} worst dev={deviation(assign):.1%} "
f"pp={[round(polsby_popper(assign, t), 2) for t in range(K)]}")
assign = grow(seeds(K))
report("grown ", assign)
assign = swap(assign)
report("swapped", assign)Output on the 57 Austin-area ZCTAs. It took 21 seconds on an Apple-silicon laptop, almost all of it rebuilding territory outlines for the compactness score on every candidate move; cache those unions per territory before you scale this to thousands of ZCTAs.
grown : loads=[479635, 319066, 503076, 489846] max/min=1.577 worst dev=28.8% pp=[0.13, 0.25, 0.18, 0.07]
swapped: loads=[452615, 444799, 446730, 447479] max/min=1.018 worst dev=1.1% pp=[0.16, 0.15, 0.17, 0.09]Reading the results
| Stage | Populations | Max / min | Worst deviation | Polsby–Popper |
|---|---|---|---|---|
| After region growing | 479,635 / 319,066 / 503,076 / 489,846 | 1.577 | 28.8% | 0.13 · 0.25 · 0.18 · 0.07 |
| Swap search, balance only (λ = 0) | 452,615 / 451,808 / 443,584 / 443,616 | 1.020 | 1.1% | 0.16 · 0.14 · 0.12 · 0.08 |
| Swap search, λ = 0.25 (published code) | 452,615 / 444,799 / 446,730 / 447,479 | 1.018 | 1.1% | 0.16 · 0.15 · 0.17 · 0.09 |
Growing alone leaves one territory 29% short of the target, because greedy growth gets boxed in. The swap search fixes the balance. With balance as the only goal (λ = 0) it gets there by trading shape: the worst territory’s Polsby–Popper drops to 0.08 and two others get thinner. Adding the compactness term reaches the same 1.1% worst deviation while keeping every territory at least as compact as the balance-only run. That is the trade you are tuning with λ.
Before you accept a plan, check:
- The max/min ratio and the worst deviation, not just the average.
- Contiguity, recomputed on the final assignment (the code asserts it on every move, but recheck after manual edits).
- Sensitivity: rerun with different seeds. If territories swing wildly, your workload measure is too lumpy for k, or a few huge ZCTAs dominate.
- A map. Numbers that look balanced can still put a river or a mountain between a rep and half their territory.
Pitfalls
- Population is not workload. Accounts, revenue potential or drive time to visit usually matter more. Swap the
popcolumn; the algorithm does not care. - Rural ZCTAs are huge and indivisible here. If one ZCTA holds more than the target load, no partition can balance it; split it with block groups.
- Islands break contiguity. The assert at the top catches them. Solve each connected component separately or add explicit ferry/bridge links.
- ZCTAs change at each census. Store which vintage a territory plan uses.
- Distance-based balance needs travel times, not centroid distance. The isochrone guide shows how far straight-line assumptions drift.
When this is the wrong choice
- You have hard constraints this ignores (existing account ownership, rep home locations, legal boundaries): use a solver with explicit constraints, or spopt with a custom objective.
- Your territories are a handful of counties: draw them by hand and check the numbers in a spreadsheet.
- You want to draw and adjust ZIP territories on a map without code: IsochroneMaps does that in the browser (built by the same team as Speaking of GIS).