Skip to main content

Spatial Joins, Overlay, and Dissolve

Spatial operations answer different questions. A spatial join transfers attributes between matching features while retaining a chosen side's geometry. Overlay constructs new geometries from two layers. Dissolve groups features and unions their geometry while aggregating attributes. None is simply “merge by location.”

Prerequisites​

Complete working with GeoPandas and Shapely. Validate both inputs and place them in equivalent CRSs before combining them.

Learning goals​

  • Select a spatial-join predicate from an explicit boundary policy.
  • Predict one-to-many output rows and audit join cardinality.
  • Distinguish join, overlay, and dissolve geometry behavior.
  • Prevent implicit invalid-geometry repair and accidental attribute aggregation.

Predicates determine membership​

The boundary-stop point lies exactly on the shared edge of the west and east districts. With predicate="intersects", it matches both polygons because it shares a boundary point with each. With point-left predicate="within", it matches neither because it is not in either polygon interior. A business rule such as “assign each address to exactly one district” therefore needs an authoritative boundary convention or explicit tie resolution; geometry alone yields two or zero matches depending on the predicate.

Always profile cardinality by stable left ID: unmatched, one match, and multiple matches. A left join preserves unmatched features but may duplicate a left feature when several right features match. Counting result rows as places would then overcount.

Overlay creates intersection, union, identity, difference, or symmetric-difference pieces and combines attributes. GeoPandas overlay defaults to make_valid=True; this batch validates first and passes make_valid=False so invalid input raises instead of being silently repaired. keep_geom_type must also be deliberate because intersections can produce lines or points from polygon boundaries.

Dissolve unions geometry by group and aggregates other columns. Default attribute aggregation may not match the domain: populations might sum, rates might need weighted means, labels might conflict, and stable feature IDs generally cannot be concatenated without a defined rule.

Worked example​

import json
from pathlib import Path

import geopandas as gpd
from shapely.geometry import box

fixture = Path("tests/fixtures/geospatial-data-science")

def load(name):
document = json.loads((fixture / name).read_text(encoding="utf-8"))
return gpd.GeoDataFrame.from_features(document["features"], crs=document["metadata"]["crs"])

places = load("places.geojson")
districts = load("districts.geojson")
assert districts.geometry.is_valid.all()
intersects = places.sjoin(districts[["district_id", "geometry"]], how="inner", predicate="intersects")
within = places.sjoin(districts[["district_id", "geometry"]], how="inner", predicate="within")
boundary_matches = sorted(intersects.loc[intersects["place_id"] == "boundary-stop", "district_id"])
service = gpd.GeoDataFrame(
{"service": ["core"]},
geometry=[box(13.39, 52.515, 13.41, 52.525)],
crs=districts.crs,
)
pieces = gpd.overlay(districts, service, how="intersection", keep_geom_type=True, make_valid=False)
dissolved = districts.dissolve(by="metro_id", aggfunc={"district_id": "count"})
print(f"intersects_rows={len(intersects)} boundary_matches={boundary_matches}")
print(f"within_rows={len(within)} boundary_within={int((within['place_id'] == 'boundary-stop').sum())}")
print(f"overlay_pieces={len(pieces)} dissolved_features={len(dissolved)}")

Expected output:

intersects_rows=5 boundary_matches=['east', 'west']
within_rows=3 boundary_within=0
overlay_pieces=2 dissolved_features=1

The five intersecting rows represent four matched places because the boundary point appears twice. The north kiosk is unmatched, and the uncategorized site's missing attribute survives the spatial logic.

Audit every combination​

Record input and output counts, unmatched and multi-match counts, geometry types, validity, empty geometries, total bounds, and a few named boundary cases. For overlay, compare area accounting in a suitable projected CRS and explain gaps or overlaps. For dissolve, name every aggregation and retain the member IDs used to create each group.

Do not use a nearest join to force every record into a polygon. Nearest answers proximity, not containment, and can assign far-away or equidistant features unless a maximum distance and tie policy are defined.

Limitations and common mistakes​

  • intersects is broad; it includes boundary contact and overlap.
  • One-to-many matches change the row grain even when the left geometry is retained.
  • Layers can share a CRS label yet have bad coordinates or incompatible observation times.
  • Overlay may create slivers from precision differences and may change geometry type.
  • Dissolve can hide internal gaps, overlaps, and conflicting attributes.

Practice​

Specify a deterministic policy for the boundary stop. Compare authoritative address assignment, covers, within, and centroid-based assignment. Identify which alternatives answer a different question or can fail on other geometries.

Next steps​

Next, measure distance, area, and nearest neighbors only after choosing units, geometry support, and a tie policy.

Primary sources​

Checked 2026-10-18: GeoPandas, merging data and spatial joins, overlay, and dissolve; Shapely 2.2, predicate definitions.