I'm computing some zonal statistics, and was comparing the results obtained using the GDAL cookbook example code here with the rasterstats zonal_stats function.

I want to compute the mean value per polygon, as well as the number of raster pixels that contributed to that calculation. I think rasterstats gives you the number of contributing pixels with their 'count' statistic.

I'm not sure how to get that with the GDAL code, though. I first thought that's what their 'numpoints' variable was counting, but their numpoints corresponds to the number of points within a ring, and I think that means the number of vertices of the ring (please correct me if I'm wrong).

Can anyone explain how to compute the number of raster pixels contributing to the GDAL cookbook calculation? Counting the number of pixels of their 'zoneraster' array variable doesn't come close to agreeing with the rasterstats count, either.

  • 3
    One easy way to obtain counts is to perform a zonal sum of a unit grid (all cells contain the value 1) using the same zones. Often a unit grid can be obtained by equating the original value grid with itself, because the software typically evaluates true to 1 and false to 0. This is a good approach because it accounts correctly for any NoData cells in the original value grid.
    – whuber
    May 30, 2015 at 19:44
  • Thanks - I like that suggestion a lot. I can accept it as a solution if you want to post it as an answer. Jun 1, 2015 at 1:17


Your Answer

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

Browse other questions tagged or ask your own question.