Spatial Data Analysis with GeoPandas
Every GPS trace, delivery address, store location, and census tract carries a coordinate. Tabular tools treat those coordinates as two anonymous numbers, which hides the single most useful property of spatial data: near things tend to be related. Spatial analysis makes that relationship explicit â it lets you ask which events fall inside a region, how far apart two stores are, whether crime clusters in a neighborhood, and what value an unsampled location likely holds.
This lesson builds a practical workflow in Python. You will learn to construct GeoDataFrames, reason about coordinate reference systems (CRS), run buffer and distance operations, join points to polygons, estimate continuous density surfaces, and test whether a variable is spatially clustered rather than randomly scattered. The stack is GeoPandas on top of Shapely, with SciPy and PySAL for the statistical pieces.
What You'll Learn
- 1Build GeoDataFrames from raw lat/lon tables and attach a correct CRS
- 2Reproject data between geographic and projected systems without breaking distances
- 3Perform spatial joins, buffers, and nearest-neighbor queries with GeoPandas
- 4Estimate density surfaces and test spatial autocorrelation with Moran's I
Prerequisites
- !Comfortable with pandas DataFrames
- !Basic Python and NumPy
- !Introductory statistics (means, variance, p-values)
Why coordinates alone are not enough
A CSV with columns lat and lon looks analytically ready, but three traps sit between it and a correct answer. First, units: decimal degrees are angular, not metric. A buffer of 0.001 degrees is roughly 111 meters at the equator and only about 78 meters at 40° latitude, so any radius expressed in degrees silently changes meaning with location. Second, distance distortion: straight-line distance in degrees is not distance on the ground; road distance, great-circle distance, and projected distance are three different numbers. Third, topology: points, lines, and polygons support different operations. You cannot meaningfully intersect two points, and you cannot buffer a polygon "inward" without a signed-distance convention.
The practical consequence shows up in real projects constantly. A retailer computing "stores within 5 km of a new mall" using raw degrees gets a wrong catchment area. An epidemiologist mapping disease incidence by neighborhood needs polygon-level denominators (population), not raw case counts, or wealthy large tracts drown out dense small ones. Spatial libraries encode the right units and topologies so these mistakes become hard to make.
GeoDataFrames: the core data structure
GeoPandas extends pandas with a GeoDataFrame, a table where one column holds Shapely geometry objects and the frame carries a coordinate reference system. Everything else â filtering, grouping, merging â works like ordinary pandas.
import numpy as np
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point, LineString, Polygon
# Build points from a raw events table
rng = np.random.default_rng(42)
n = 800
events = pd.DataFrame({
"event_id": range(n),
"store_id": rng.integers(0, 25, n),
"sales": rng.lognormal(mean=5.2, sigma=0.8, size=n).round(2),
"lon": rng.uniform(-74.02, -73.75, n),
"lat": rng.uniform(40.68, 40.82, n),
})
geometry = [Point(xy) for xy in zip(events["lon"], events["lat"])]
gdf = gpd.GeoDataFrame(events, geometry=geometry, crs="EPSG:4326")
print(gdf.crs) # EPSG:4326 (WGS84 lon/lat)
print(gdf.geometry.geom_type.value_counts())
print(gdf.total_bounds) # minx, miny, maxx, maxy
The crs argument is the difference between a defensible analysis and a decorative map. EPSG:4326 is the GPS standard â degrees on a sphere. Most measurement work, however, wants a projected CRS in meters.
Choosing and applying coordinate reference systems
A projected CRS flattens a region of the earth onto a plane, trading global accuracy for local accuracy. The right choice depends on your extent. For city- or metro-scale work in the United States, a State Plane zone is ideal. For broader regional work, a Universal Transverse Mercator (UTM) zone fits well. For web maps, Web Mercator (EPSG:3857) is the display standard but stretches distances at high latitude, so never measure with it.
| Task | Recommended CRS | Units | Notes |
|---|---|---|---|
| GPS collection, exchange | EPSG:4326 | degrees | Universal interchange format |
| City-scale distances/buffers | State Plane (e.g. EPSG:2263) | feet or meters | Minimal local distortion |
| Regional analysis (one UTM zone) | EPSG:326xx / 327xx | meters | Good balance of accuracy |
| Whole-country choropleths | Equal-area (e.g. EPSG:5070) | meters | Preserves area comparisons |
| Slippy web maps | EPSG:3857 | pseudo-meters | Display only â do not measure |
Reprojection in GeoPandas is one call:
# Degrees -> meters (UTM zone 18N covers New York City)
gdf_utm = gdf.to_crs(epsg=32618)
# Sanity check: coordinates should now be large meter values
print(gdf_utm.total_bounds)
# Buffers in meters are now meaningful
gdf_utm["buffer_500m"] = gdf_utm.geometry.buffer(500)
print(gdf_utm["buffer_500m"].area.head())
# Pairwise distance between the first two events, in meters
d = gdf_utm.geometry.iloc[0].distance(gdf_utm.geometry.iloc[1])
print(f"Distance: {d:.1f} m")
A common production pattern is to store everything in EPSG:4326 at rest, reproject a working copy for measurement, then reproject back before writing to a mapping layer. Keeping one canonical storage CRS avoids the classic bug of comparing a degree geometry to a meter geometry â GeoPandas will raise a warning, but scripts that ignore warnings ship wrong numbers.
Spatial joins: linking points to regions
Spatial joins answer containment and proximity questions: which district is each delivery in, which stores are within 2 km of each event, how many events fall in each polygon. GeoPandas implements them with sjoin and a predicate (within, contains, intersects, nearest, and others).
# Define neighborhood polygons covering the study area
regions = gpd.GeoDataFrame(
{
"region_id": [1, 2, 3, 4],
"region_name": ["North", "Central", "East", "South"],
"population": [52000, 81000, 44000, 63000],
"geometry": [
Polygon([(-74.02, 40.78), (-73.88, 40.78), (-73.88, 40.82), (-74.02, 40.82)]),
Polygon([(-74.02, 40.74), (-73.88, 40.74), (-73.88, 40.78), (-74.02, 40.78)]),
Polygon([(-73.95, 40.68), (-73.88, 40.68), (-73.88, 40.74), (-73.95, 40.74)]),
Polygon([(-74.02, 40.68), (-73.95, 40.68), (-73.95, 40.74), (-74.02, 40.74)]),
],
},
crs="EPSG:4326",
)
# Point-in-polygon join
joined = gpd.sjoin(gdf, regions, how="left", predicate="within")
# Aggregate to region level for a rate map (counts alone mislead)
region_stats = (
joined.groupby("region_name")
.agg(events=("event_id", "count"), total_sales=("sales", "sum"))
.reset_index()
.merge(regions[["region_name", "population"]], on="region_name")
)
region_stats["sales_per_capita"] = region_stats["total_sales"] / region_stats["population"]
print(region_stats.sort_values("sales_per_capita", ascending=False))
Note the aggregation choice: raw sales per region mostly reflects population. Dividing by an exposure variable turns a volume map into an intensity map â the quantity you actually want to compare across regions of unequal size. This is the spatial version of adjusting for base rates.
Nearest neighbors and distance bands
Buffering answers "what is within X", while nearest-neighbor analysis answers "how far to the closest one". For repeated distance queries, a cKDTree from SciPy is far faster than naive pairwise loops, and sjoin with predicate="nearest" offers a pure-GeoPandas route.
from scipy.spatial import cKDTree
coords = np.column_stack([gdf_utm.geometry.x, gdf_utm.geometry.y])
tree = cKDTree(coords)
# Distance to 1st and 2nd nearest neighbor for every event
dists, idxs = tree.query(coords, k=3)
gdf_utm["nn1_m"] = dists[:, 1]
gdf_utm["nn2_m"] = dists[:, 2]
print(gdf_utm["nn1_m"].describe())
# Flag spatial outliers: points whose nearest neighbor is far away
threshold = gdf_utm["nn1_m"].quantile(0.95)
outliers = gdf_utm[gdf_utm["nn1_m"] > threshold]
print(f"{len(outliers)} events beyond {threshold:.0f} m of any neighbor")
The nearest-neighbor distance distribution is a quick diagnostic for clustering. If events were uniformly random over the study area, average nearest-neighbor distance follows a known relationship with density; a much smaller observed average is evidence of clustering, which formal tests confirm.
Density surfaces with kernel density estimation
Point clouds are hard to compare; a continuous surface is easy to map and interpolate. Kernel density estimation (KDE) places a smooth bump at each point and sums the bumps to produce a density field.
from scipy.stats import gaussian_kde
x = gdf_utm.geometry.x.values
y = gdf_utm.geometry.y.values
kde = gaussian_kde(np.vstack([x, y]), bw_method=0.08)
# Evaluate on a regular grid for contouring or raster export
gx = np.linspace(x.min(), x.max(), 120)
gy = np.linspace(y.min(), y.max(), 120)
GX, GY = np.meshgrid(gx, gy)
positions = np.vstack([GX.ravel(), GY.ravel()])
density = kde(positions).reshape(GX.shape)
peak = np.unravel_index(np.argmax(density), density.shape)
print(f"Peak density at x={GX[peak]:.0f}, y={GY[peak]:.0f}")
print(f"Density range: {density.min():.2e} .. {density.max():.2e}")
# Export a smooth surface as points for GIS tools
surface = gpd.GeoDataFrame(
{"density": density.ravel()},
geometry=gpd.points_from_xy(GX.ravel(), GY.ravel()),
crs=gdf_utm.crs,
)
Bandwidth choice dominates the result. A narrow bandwidth produces a spiky surface that memorizes each point; a wide bandwidth blurs distinct hotspots into one blob. Rule-of-thumb selectors (Silverman's rule) are a starting point, but always eyeball two or three bandwidths against a map before publishing numbers.
Spatial autocorrelation: is the pattern real?
The foundational test is Moran's I, which compares the similarity of neighbors to the overall variance. An I near its expectation under randomness means no spatial structure; a significantly positive I means similar values cluster; a significantly negative I means a checkerboard of dissimilar neighbors.
from pysal.lib import weights
from esda.moran import Moran
# k-nearest-neighbor weights, row-standardized
w = weights.KNN.from_dataframe(gdf_utm, k=8)
w.transform = "r"
moran = Moran(gdf_utm["sales"], w)
print(f"Moran's I = {moran.I:.4f} (expected {moran.EI:.4f})")
print(f"pseudo p-value = {moran.p_sim:.4f}")
if moran.p_sim < 0.05 and moran.I > moran.EI:
print("Significant positive spatial autocorrelation: sales cluster.")
else:
print("No significant spatial clustering detected.")
Positive autocorrelation has a modeling consequence that many analysts miss: ordinary least squares assumes independent residuals, and clustered residuals violate that assumption, inflating significance. Detecting spatial autocorrelation is therefore a gate before regression, not an optional curiosity â if Moran's I is significant, consider spatial lag or error models, cluster-robust standard errors, or aggregating to a coarser unit.
When (not) to use interpolation
Kriging and IDW create values at unsampled locations, which is seductive and sometimes wrong. Interpolation assumes the variable varies smoothly in space â true for elevation and soil pH, false for crime incidents driven by discrete social processes. Before interpolating, test autocorrelation at the lags you care about; if nearby points are not more similar than distant ones, an interpolated surface is fiction with a color bar.
â ī¸The MAUP trap
Results change with the aggregation level â the modifiable areal unit problem. A hotspot at the census-tract scale can vanish at the county scale. Always report the unit of analysis, and check that key findings survive at least one alternative aggregation.
Common Mistakes
Buffering or measuring distance while the GeoDataFrame is still in EPSG:4326 degrees
Fix: Reproject to a metric CRS first (UTM or State Plane), then buffer and measure; convert back for storage or web display.
Mapping raw counts per region and concluding 'this neighborhood is hot'
Fix: Divide by an exposure variable (population, store count, area) to get a rate, and test whether the pattern is statistically clustered.
Interpolating a variable with no spatial autocorrelation
Fix: Run Moran's I before kriging or KDE-based inference; if the pattern is random, report it as random.
Ignoring boundary effects â points near the study edge have fewer neighbors
Fix: Use k-nearest-neighbor weights instead of fixed-distance bands, or trim a border buffer before computing statistics.
Best Practices
- Store data in EPSG:4326 and reproject a working copy for measurement â one canonical storage CRS prevents unit mix-ups
- Pair every choropleth with a rate and an exposure variable, not raw counts
- Validate interpolated surfaces with spatial cross-validation (hold out contiguous blocks, not random points)
- Record the CRS in every file you share; shapefiles drop it silently, GeoPackage and GeoJSON with explicit CRS do not
- Combine global tests (Moran's I) with local indicators (LISA) to locate clusters, not just detect them
Interview Questions
Q1: Why can you not buffer a geometry in EPSG:4326?
Coordinates are angular degrees, so a numeric buffer has no consistent physical meaning; at 40° latitude one degree of longitude is roughly 85 km while one degree of latitude stays near 111 km. Project to a metric CRS, buffer, then reproject back.
Q2: What is the difference between spatial autocorrelation and ordinary correlation?
Ordinary correlation measures linear association between two variables across observations. Spatial autocorrelation measures association between a variable and itself at neighboring locations, using a spatial weights matrix.
Q3: When is kriging inappropriate?
When the variable lacks spatial autocorrelation at the lags being interpolated, when the sampling design is strongly biased, or when the underlying process is discrete rather than smoothly varying.
Key Takeaways
- GeoDataFrames pair pandas tables with Shapely geometry and an explicit CRS; the CRS is part of the data, not metadata you can ignore
- Reproject to a metric CRS (UTM, State Plane) before any buffer, area, or distance calculation
- Spatial joins with predicates like within and nearest convert geometry into analyzable attributes; aggregate to rates, not raw counts
- KDE turns point clouds into continuous surfaces, but bandwidth choice and autocorrelation checks decide whether the surface is meaningful
- Moran's I tests whether clustering is real; significant autocorrelation invalidates the independence assumption of standard regression