[GIS] Geopandas: counting the number of raster pixels within a shapefile polygon

geometrygeopandasshapefile

I have a shapefile that I have loaded as a geopandas dataframe, 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 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 dataframe, is there a way to compute the number of raster pixels inside each polygon?

Best Answer

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

from rasterstats import zonal_stats
import geopandas as gpd
geodf = gpd.read_file("foo.shp")
zonal_stats(geodf, "bar.tif")

There are some good examples of rasterstats integration on the wiki

Related Question