Zonal Statistics
Zonal statistics summarize raster values for polygons: for example, mean temperature by district. The arithmetic is easy; the hard part is defining which cells belong, what the values represent, and whether the aggregate supports the intended claim.
Prerequisites
Complete windowed raster processing and spatial joins, overlay, and dissolve. You should know the raster grid contract and polygon CRS before masking.
Learning goals
- Align zones and rasters in the same declared CRS.
- Choose and report centre-based versus all-touched pixel inclusion.
- Exclude NoData without treating it as zero and report valid coverage.
- Match sum, mean, count, or weighted aggregation to the variable's spatial support.
Define membership before aggregation
Rasterio's default mask includes a pixel when its centre lies inside a polygon (with a line-specific exception); all_touched=True includes every touched pixel. Neither policy is universally correct. Small, thin, or boundary-aligned zones can change substantially between them. Record the rule and run sensitivity checks where it matters.
The temperature band is intensive: averaging valid cells is meaningful only as an equal-cell-area summary over covered raster support. Population counts are extensive and are not safely averaged. If cells are partially covered or have unequal area, weights may be required. A district mean does not imply that everyone or every point in the polygon experienced that value.
Coverage belongs beside the statistic. Count valid and expected cells or area, surface missingness, and avoid comparing zones with materially different coverage without qualification. NoData is not zero, and masking must happen before applying the scale factor.
Worked example
import json
from pathlib import Path
import geopandas as gpd
import rasterio
from rasterio.mask import mask
fixture = Path("tests/fixtures/geospatial-data-science")
document = json.loads((fixture / "districts.geojson").read_text(encoding="utf-8"))
districts = gpd.GeoDataFrame.from_features(document["features"], crs=document["metadata"]["crs"])
results = []
with rasterio.open(fixture / "tiny-multiband.tif") as raster:
zones = districts.to_crs(raster.crs)
for row in zones.sort_values("district_id").itertuples():
values, _ = mask(raster, [row.geometry], indexes=1, crop=False, filled=False, all_touched=False)
band = values[0]
results.append((row.district_id, band.count(), float(band.mean()) / 10))
print(f"crs={raster.crs.to_string()} inclusion=pixel-center all_touched=False nodata={raster.nodata}")
for district_id, count, mean_c in results:
print(f"{district_id}_valid_cells={count} mean_temperature_c={mean_c:.2f}")
Expected output:
crs=EPSG:32633 inclusion=pixel-center all_touched=False nodata=-9999.0
east_valid_cells=3 mean_temperature_c=19.00
west_valid_cells=1 mean_temperature_c=18.00
The vector zones are reprojected to the raster's CRS; the raster transform and extent remain unchanged. The result is an equal-area cell-centre summary for this synthetic fixture, not an estimate of people exposed and not a benchmark.
Limitations and common mistakes
- Reproject vectors to the raster for masking; reprojecting the raster unnecessarily adds another resampling step.
- Boundary inclusion can dominate tiny zones; publish the policy and sensitivity.
- Means hide distributions, coverage gaps, temporal mismatch, and within-zone heterogeneity.
- Correlated neighboring pixels do not create independent evidence merely because the cell count is large.
- Never infer individual outcomes from an area aggregate; spatial coincidence does not establish causal influence.
Practice
Repeat the design for a population-count raster and a vegetation-class raster. Choose an aggregation for each, define partial-cell handling, and specify the coverage field that must accompany every output row.
Next steps
Next, learn how spatial indexes generate candidates while exact geometry predicates still decide matches.
Primary sources
Checked 2026-10-18: Rasterio API, mask and all_touched; Rasterio, NoData masks; GeoPandas, projection guidance; GDAL, raster data model.