I have a shapefile that I have loaded as a GeoPandas GeoDataFrame, and it has a geometry column containing polygons and multipolygons.

My end goal is to do some zonal computations on a GeoTiff raster, in particular, I want to compute the mean value within each polygon, and also count the number of pixels that contributed to that polygon's zonal mean. Here's a link to another GIS-SE question of mine that outlines my attempts to do that so far using GDAL and rasterstats.

I am just wondering if GeoPandas is up to zonal calculations yet. If I open a raster in GDAL/numpy/rasterio and load the shapefile in a GeoPandas GeoDataFrame, is there a way to compute the number of raster pixels inside each polygon?

  • Could you clarify what you mean by 'count the number of pixels'?
    – juturna
    Commented May 29, 2015 at 13:43
  • My apologies, I'm new to GIS and wasn't thinking straight. Obviously the shapefile doesn't have pixels, I was thinking of the GeoTiff raster I want to overlay. I'll delete this question Commented May 29, 2015 at 14:16
  • So you are looking for the number of pixels in the raster within each polygon? You can edit your question to clarify what you are asking.
    – juturna
    Commented May 29, 2015 at 14:23

2 Answers 2


You can do zonal statistics from a GeoDataFrame directly on a GeoTiff using rasterstats.

import geopandas as gpd
from rasterstats import zonal_stats

geodf = gpd.read_file("foo.shp")
zonal_stats(geodf, "bar.tif")

There are some good examples of rasterstats integration on the wiki.

  • Yes - I did go with rasterstats in the end and it works great. Commented Oct 26, 2015 at 18:29
  • do these stats reflect the values of the pixels? or their area?
    – fccoelho
    Commented Dec 3, 2016 at 17:35
  • @fccoelho Zonal statistics are descriptive statistics (mean, median, min, max, etc) of the set of pixels which intersect a geometry. Thus both the number of pixels (roughly equivalent to the area of the geometry) and the value of those pixels are considered.
    – perrygeo
    Commented Dec 4, 2016 at 23:33

By "count the number of pixels" do mean the area of each polygon? If so,

  • 2
    Thanks for your answer. My question didn't make any sense, so I've updated it. Commented May 29, 2015 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.