1

I am using the rasterstats python package for calculating the zonal statistics of vector geometries with a raster layer like this:

stats = zonal_stats('tests/data/polygons.shp', 'tests/data/slope.tif',stats="count", all_touched=true)

Is it possible to calculate the weighted mean of the pixels like: if a pixel has an overlap 50 % with the shape then it gets a weight of 0.5 and if the pixel lies fully within the polygon it gets weight 1.

1 Answer 1

2

I don't think rasterstats supports partially overlapping polygons (it works with a rasterisation strategy). Most competing zonal statistics tools don't consider partial overlap, or do so very slowly. However one that does (and does it very quickly) is exactextract. I recommend switching tools if you need this.

6
  • Does this work with netcdf file too? Commented Aug 4, 2023 at 1:42
  • Yes, if you read the project README it has an example of accessing NetCDF variables. Commented Aug 4, 2023 at 1:43
  • Oh wow. This looks supercool. I will give it a try. Commented Aug 4, 2023 at 1:47
  • If only exactextract was an actual package that could be installed easily and had python bindings. Seems like that's on their roadmap but it's not useable currently unless you compile it yourself (or if you use r, as there's the exactextractr library which is a port of/bindings for? exactextract).
    – user2856
    Commented Aug 4, 2023 at 3:48
  • That's right. It's still very straightforward to install on Linux, but that may not be to everyone's taste. However, it is remarkably better than the alternatives at this point. Commented Aug 6, 2023 at 21:48

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.