Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

zonal stats on a categorical raster #91

Open
dcherian opened this issue Jan 21, 2025 · 2 comments
Open

zonal stats on a categorical raster #91

dcherian opened this issue Jan 21, 2025 · 2 comments

Comments

@dcherian
Copy link
Contributor

I just had someone ask about zonal_stats with a categorical raster where the only "stat" that makes sense is a count (or perhaps area). Example: https://pythonhosted.org/rasterstats/manual.html?highlight=categorical#working-with-categorical-rasters

Is this supported or straightforward to implement?

@martinfleis
Copy link
Member

aggregations can be specified using a string representing an aggregation method available as DataArray/Dataset or *GroupBy methods like DataArray.mean, DataArray.min or DataArray.max. Alternatively, you can pass a callable accepted by DataArray/Dataset.reduce. Alternatively, you can pass a tuple in a format (name, func) where name is used as a coordinate and func is either known string as above or a callable, or (name, func, {kwargs}), if you need to pass additional keyword arguments.

From https://xvec.readthedocs.io/en/stable/zonal_stats.html#aggregation-options

With categorical data you will probably need to turn the categories to a dimension on its own and return counts per unique category, which I am not certain you can achieve with a custom func. But it should not be too complicated to implement that, we have a similar logic for quantiles for example if you want to report multiple.

@dcherian
Copy link
Contributor Author

For the rasterize version this could "just" become a multi-variable GroupBy:

groups = acc._obj.groupby(xr.DataArray(labels, dims=(y_coords, x_coords)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants