diff --git a/docs/manual.rst b/docs/manual.rst index 15225a4..2a05496 100644 --- a/docs/manual.rst +++ b/docs/manual.rst @@ -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 ^^^^^^^^^^^^^^ diff --git a/src/rasterstats/main.py b/src/rasterstats/main.py index 5c9eb68..b1dc964 100644 --- a/src/rasterstats/main.py +++ b/src/rasterstats/main.py @@ -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 @@ -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) @@ -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) @@ -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