Skip to content

70 zonal stats

image image image

Calculating zonal statistics - summarizing geospatial raster datasets based on vector geometries

Uncomment the following line to install leafmap if needed.

1
# %pip install -U leafmap
1
# %pip install -U rasterstats geopandas
1
2
import leafmap
import geopandas as gpd
1
2
3
dsm = "https://opengeos.org/data/elevation/dsm.tif"
hag = "https://opengeos.org/data/elevation/hag.tif"
buildings = "https://raw.githubusercontent.com/opengeos/data/refs/heads/main/elevation/buildings.geojson"
1
2
3
4
5
m = leafmap.Map()
m.add_cog_layer(dsm, name="DSM", palette="terrain")
m.add_cog_layer(hag, name="Height Above Ground", palette="magma")
m.add_geojson(buildings, layer_name="Buildings")
m
1
2
gdf = gpd.read_file(buildings)
len(gdf)
1
gdf.head()

The leafmap.zonal_stats() function wraps the rasterstats.zonal_stats() function and performs reprojection if necessary.

By default, the zonal_stats function will return the following statistics:

  • min
  • max
  • mean
  • count
  • Optionally, these statistics are also available.

  • sum

  • std
  • median
  • majority
  • minority
  • unique
  • range
  • nodata
1
2
stats = leafmap.zonal_stats(gdf, hag, stats=["min", "max", "mean", "count"])
len(stats)
1
stats[:5]
1
2
stats_geojson = leafmap.zonal_stats(gdf, hag, stats=["mean", "count"], geojson_out=True)
len(stats_geojson)
1
stats_geojson[0]
1
2
stats_gdf = leafmap.zonal_stats(gdf, hag, stats=["mean", "count"], gdf_out=True)
len(stats_gdf)
1
stats_gdf.head()
1
2
3
m = leafmap.Map()
m.add_gdf(stats_gdf, layer_name="Zonal Stats")
m