Skip to content
Speaking of GIS

Data & algorithms

Balancing Sales Territories with US Census ZCTA Polygons

ZCTAs are not ZIP codes. Here is what they are, and a contiguous balancing algorithm in Python that took 57 Austin-area ZCTAs from a 1.58 to a 1.02 max/min split.

Last tested
Level
Advanced
Versions
Python 3.13 · GeoPandas 1.2.0 · libpysal 4.15.1 · NetworkX 3.7 · TIGERweb 2020 Census ZCTAs

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 78610: 45,134 people (2020 Census), territory 2ZCTA 78612: 16,265 people (2020 Census), territory 4ZCTA 78613: 89,279 people (2020 Census), territory 3ZCTA 78617: 28,832 people (2020 Census), territory 4ZCTA 78634: 37,951 people (2020 Census), territory 4ZCTA 78641: 83,426 people (2020 Census), territory 3ZCTA 78645: 14,051 people (2020 Census), territory 3ZCTA 78652: 5,831 people (2020 Census), territory 2ZCTA 78653: 31,167 people (2020 Census), territory 4ZCTA 78660: 110,955 people (2020 Census), territory 1ZCTA 78664: 60,287 people (2020 Census), territory 1ZCTA 78665: 61,577 people (2020 Census), territory 4ZCTA 78681: 57,503 people (2020 Census), territory 3ZCTA 78701: 11,625 people (2020 Census), territory 4ZCTA 78702: 25,910 people (2020 Census), territory 4ZCTA 78703: 22,194 people (2020 Census), territory 2ZCTA 78704: 49,197 people (2020 Census), territory 2ZCTA 78705: 36,535 people (2020 Census), territory 4ZCTA 78712: 351 people (2020 Census), territory 4ZCTA 78717: 36,987 people (2020 Census), territory 3ZCTA 78719: 2,004 people (2020 Census), territory 4ZCTA 78721: 11,316 people (2020 Census), territory 4ZCTA 78722: 6,618 people (2020 Census), territory 4ZCTA 78723: 34,522 people (2020 Census), territory 4ZCTA 78724: 29,680 people (2020 Census), territory 4ZCTA 78725: 10,301 people (2020 Census), territory 4ZCTA 78726: 15,618 people (2020 Census), territory 3ZCTA 78727: 29,928 people (2020 Census), territory 1ZCTA 78728: 25,555 people (2020 Census), territory 1ZCTA 78729: 31,829 people (2020 Census), territory 1ZCTA 78730: 9,403 people (2020 Census), territory 3ZCTA 78731: 27,240 people (2020 Census), territory 2ZCTA 78732: 19,128 people (2020 Census), territory 3ZCTA 78733: 9,347 people (2020 Census), territory 3ZCTA 78734: 22,963 people (2020 Census), territory 3ZCTA 78735: 20,983 people (2020 Census), territory 3ZCTA 78736: 10,165 people (2020 Census), territory 3ZCTA 78737: 20,996 people (2020 Census), territory 2ZCTA 78738: 29,529 people (2020 Census), territory 3ZCTA 78739: 21,854 people (2020 Census), territory 2ZCTA 78741: 49,344 people (2020 Census), territory 4ZCTA 78742: 964 people (2020 Census), territory 4ZCTA 78744: 51,048 people (2020 Census), territory 2ZCTA 78745: 59,843 people (2020 Census), territory 2ZCTA 78746: 29,106 people (2020 Census), territory 2ZCTA 78747: 21,891 people (2020 Census), territory 2ZCTA 78748: 55,226 people (2020 Census), territory 2ZCTA 78749: 35,239 people (2020 Census), territory 2ZCTA 78750: 28,348 people (2020 Census), territory 3ZCTA 78751: 17,071 people (2020 Census), territory 4ZCTA 78752: 19,289 people (2020 Census), territory 1ZCTA 78753: 58,761 people (2020 Census), territory 1ZCTA 78754: 27,020 people (2020 Census), territory 4ZCTA 78756: 8,426 people (2020 Census), territory 4ZCTA 78757: 23,847 people (2020 Census), territory 1ZCTA 78758: 49,831 people (2020 Census), territory 1ZCTA 78759: 42,333 people (2020 Census), territory 1Territory (2020 pop.)1 · 452,6152 · 444,7993 · 446,7304 · 447,479ZCTA boundaries: US Census Bureau, TIGERweb (2020)
57 Austin-area ZCTAs split into four contiguous territories by the algorithm in this guide. Populations: territory 1 452,615, territory 2 444,799, territory 3 446,730, territory 4 447,479.

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 POP100 and HU100 (2020 population and housing units), so one request gets shapes and counts together. That is what we used:
shell
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.geojson

That 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:

  1. Contiguous: each territory is one connected piece, under queen contiguity (sharing any boundary point counts as adjacent).
  2. Balanced: the largest deviation from the mean workload is small. We used population; use whatever drives the work.
  3. 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

  1. Seed k territories far apart: start from the most populous ZCTA, then repeatedly add the ZCTA farthest from all chosen seeds.
  2. 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.
  3. 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.
balance.py (Python 3.13, GeoPandas 1.2.0, libpysal 4.15.1, NetworkX 3.7)
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.

output
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

StagePopulationsMax / minWorst deviationPolsby–Popper
After region growing479,635 / 319,066 / 503,076 / 489,8461.57728.8%0.13 · 0.25 · 0.18 · 0.07
Swap search, balance only (λ = 0)452,615 / 451,808 / 443,584 / 443,6161.0201.1%0.16 · 0.14 · 0.12 · 0.08
Swap search, λ = 0.25 (published code)452,615 / 444,799 / 446,730 / 447,4791.0181.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 pop column; 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).

Found an error or a step that no longer works? Write to info@adeptaoperations.com; we correct guides and note the change date. More in the guide index.