Skip to content

Commit

Permalink
Proposition to give access to geometry properties within the user-def…
Browse files Browse the repository at this point in the history
…ined stats. docs modification
  • Loading branch information
Gilles Plessis committed Jun 15, 2019
1 parent 910455c commit 1db2a33
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
14 changes: 14 additions & 0 deletions docs/manual.rst
Expand Up @@ -174,6 +174,20 @@ then use it in your ``zonal_stats`` call like so::
... add_stats={'mymean':mymean})
[{'count': 75, 'mymean': 14.660084635416666}, {'count': 50, 'mymean': 56.605761718750003}]

To have access to geometry properties, a dictionnary can be passed to the user-defined function::

>>> def mymean_prop(x,prop):
... return np.ma.mean(x) * prop['id']

then use it in your ``zonal_stats`` call like so::

>>> zonal_stats("tests/data/polygons.shp",
... "tests/data/slope.tif",
... stats="count",
... add_stats={'mymean_prop':mymean_prop},
... properties=['id'])
[{'count': 75, 'mymean_prop': 14.660084635416666}, {'count': 50, 'mymean_prop': 113.2115234375}]


GeoJSON output
^^^^^^^^^^^^^^
Expand Down
13 changes: 11 additions & 2 deletions src/rasterstats/main.py
Expand Up @@ -45,7 +45,8 @@ def gen_zonal_stats(
zone_func=None,
raster_out=False,
prefix=None,
geojson_out=False, **kwargs):
geojson_out=False,
properties=None, **kwargs):
"""Zonal statistics of raster values aggregated to vector geometries.
Parameters
Expand Down Expand Up @@ -112,6 +113,9 @@ def gen_zonal_stats(
with zonal stats appended as additional properties.
Use with `prefix` to ensure unique and meaningful property names.
properties: list of str, , optional
Property names of the geo-like python objects to be used in the user-defined stats.
Returns
-------
generator of dicts (if geojson_out is False)
Expand Down Expand Up @@ -146,6 +150,8 @@ def gen_zonal_stats(
features_iter = read_features(vectors, layer)
for _, feat in enumerate(features_iter):
geom = shape(feat['geometry'])
if properties:
prop_dic = {k: feat['properties'][k] for k in properties}

if 'Point' in geom.type:
geom = boxify_points(geom, rast)
Expand Down Expand Up @@ -254,7 +260,10 @@ def gen_zonal_stats(

if add_stats is not None:
for stat_name, stat_func in add_stats.items():
feature_stats[stat_name] = stat_func(masked)
try:
feature_stats[stat_name] = stat_func(masked, prop_dic)
except:
feature_stats[stat_name] = stat_func(masked)

if raster_out:
feature_stats['mini_raster_array'] = masked
Expand Down

0 comments on commit 1db2a33

Please sign in to comment.