Return whole array from zonal stats

There are some good examples of how to calculate zonal stats using geopandas and Rasterio/GDAL but all of these return a single statistic. Is there a method to return all of the pixel values so that custom statistics can be performed on the array of returned values?

``````gdf['mean'] = pd.DataFrame(
zonal_stats(
vectors=gdf['geometry'],
raster='raster.tif',
stats='mean'
)
)['mean']
``````

you would have something like:

``````gdf['All'] = pd.DataFrame(
zonal_stats(
vectors=gdf['geometry'],
raster='raster.tif',
stats='array'
)
)['array']
``````

This was originally closed as it was categorized as being answered elsewhere but the answer provided wasn't suitable (Geopandas and Zonal Statistic error). This answer does not demonstrate how to get the array.

• You can define your own stats: pythonhosted.org/rasterstats/…. Is this what you are after? Also, when you read a raster using Rasterio, you are generating a DatasetReader, which you can use to access a Numpy ndarray. From there you can calculate any summary statistics you need. More details: rasterio.readthedocs.io/en/latest/topics/…
– Aaron
Jun 9 '21 at 4:42
• @Aaron rather than the custom statistic, I'd really just like to have the array, but maybe I can achieve that by not defining a function? Otherwise I may have to look into windowed reads or something. Basically I need the pixels to pass into the next step of the workflow, rather than a single stat (e.g. mean) Jun 9 '21 at 13:09
– Aaron
Jun 9 '21 at 13:34
• @Aaron Yeah, I think I will have to read the raster as a numpy array, but doing a windowed read using the polygon as the bbox Jun 9 '21 at 13:38

If anyone needs the whole array their zonal stats are based on, I did this:

``````def my_arr(x):
return x

def main():