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?

so instead of:

gdf['mean'] = pd.DataFrame(

you would have something like:

gdf['All'] = pd.DataFrame(

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
  • How about reading the raster as a Numpy ndarray?
    – 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():

    stats = zonal_stats(file,image,stats="count",add_stats={'my_arr':my_arr}, geojson_out=True)

    data = np.ma.getdata(stats[0]['properties']['my_arr'])
    mask = np.ma.getmask(stats[0]['properties']['my_arr'])

    # Get only pixel centroids
    Arr = data[mask==False]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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