# Zonal Statistics Spatial Join Raster to Polygon in Python

• I have a data frame that consists of 3 polygons
• I have a raster with a single band

Seems like Zonal statistics as a table in ArcGIS does the job but I am using pure python script on this one; with no access to ArcPy.

how do I join the raster value (min, max, average, etc.) to the 3 polygons?

``````import geopandas as gpd

print("length of gdf: ", len(gdf))
# length of gdf: 3

def zonstats(gdf, raster_path):
...
...
...
return gdf_joined
``````

You can use `rasterstats.zonal_stats`

``````import geopandas as gpd
from rasterstats import zonal_stats

zones = "zones.shp"
values = "values.tif"

stats = gpd.GeoDataFrame(zonal_stats(gdf, values, stats=["min", "max", "mean"]))
gdf = gdf.join(stats)

``````

Example output:

``````   id                                           geometry
0   1  POLYGON ((440819.096 3751134.570, 440983.634 3...
1   2  POLYGON ((441147.373 3751255.178, 441265.585 3...
2   3  POLYGON ((441438.110 3751077.860, 441789.549 3...
3   4  POLYGON ((440808.713 3750651.340, 440925.327 3...
4   5  POLYGON ((441174.530 3750450.061, 441371.017 3...
id                                           geometry  ...    max        mean
0   1  POLYGON ((440819.096 3751134.570, 440983.634 3...  ...  173.0  133.909091
1   2  POLYGON ((441147.373 3751255.178, 441265.585 3...  ...  140.0  120.900000
2   3  POLYGON ((441438.110 3751077.860, 441789.549 3...  ...  165.0  122.714286
3   4  POLYGON ((440808.713 3750651.340, 440925.327 3...  ...  140.0  118.800000
4   5  POLYGON ((441174.530 3750450.061, 441371.017 3...  ...  173.0  122.555556
``````
• quick clarification; the `zones.shp` consists of more than 1 feature, am I correct? Commented Jun 10, 2022 at 15:23
• @sutan yes zonal_stats returns as many records as there are features Commented Jun 10, 2022 at 23:53
• If you're willing to use R from Python, the exactextractr package is much faster and does much more than rasterstats. Commented Jun 11, 2022 at 3:06
• @sermomon that comment would be better as a complete answer with an example Commented Jun 11, 2022 at 4:59
• @sermomon good to know, I'm not using R but some of my friends do. If you have an answer & example just as@user2856 suggested it'd be nice! thanks. Commented Jun 13, 2022 at 9:46