xrspatial.zonal.stats

xrspatial.zonal.stats(zones: xarray.core.dataarray.DataArray, values: xarray.core.dataarray.DataArray, zone_ids: Optional[List[Union[int, float]]] = None, stats_funcs: Union[Dict, List] = ['mean', 'max', 'min', 'sum', 'std', 'var', 'count'], nodata_values: Optional[Union[int, float]] = None) Union[pandas.core.frame.DataFrame, dask.dataframe.core.DataFrame][source]

Calculate summary statistics for each zone defined by a zones dataset, based on values aggregate.

A single output value is computed for every zone in the input zones dataset.

This function currently supports numpy backed, and dask with numpy backed xarray DataArrays.

Parameters
  • zones (xr.DataArray) – zones is a 2D xarray DataArray of numeric values. A zone is all the cells in a raster that have the same value, whether or not they are contiguous. The input zones raster defines the shape, values, and locations of the zones. An integer field in the input zones DataArray defines a zone.

  • values (xr.DataArray) – values is a 2D xarray DataArray of numeric values (integers or floats). The input values raster contains the input values used in calculating the output statistic for each zone. In dask case, the chunksizes of zones and values should be matching. If not, values will be rechunked to be the same as of zones.

  • zone_ids (list of ints, or floats) – List of zones to be included in calculation. If no zone_ids provided, all zones will be used.

  • stats_funcs (dict, or list of strings, default=['mean', 'max', 'min',) – ‘sum’, ‘std’, ‘var’, ‘count’] The statistics to calculate for each zone. If a list, possible choices are subsets of the default options. In the dictionary case, all of its values must be callable. Function takes only one argument that is the values raster. The key become the column name in the output DataFrame. Note that if zones and values are dask backed DataArrays, stats_funcs must be provided as a list that is a subset of default supported stats.

  • nodata_values (int, float, default=None) – Nodata value in values raster. Cells with nodata_values do not belong to any zone, and thus excluded from calculation.

Returns

stats_df – A pandas DataFrame, or a dask DataFrame where each column is a statistic and each row is a zone with zone id.

Return type

Union[pandas.DataFrame, dask.dataframe.DataFrame]

Examples

import numpy as np
import xarray as xr
from xrspatial.zonal import stats

height, width = 10, 10
# Values raster
values = xr.DataArray(np.arange(height * width).reshape(height, width))
# Zones raster
zones = xr.DataArray(np.zeros(height * width).reshape(height, width))
zones[:5, :5] = 0
zones[:5, 5:] = 10
zones[5:, :5] = 20
zones[5:, 5:] = 30
>>> # Calculate Stats
>>> stats_df = stats(zones=zones, values=values)
>>> print(stats_df)
    zone  mean  max  min   sum       std    var  count
0   0    22.0   44    0   550  14.21267  202.0     25
1  10    27.0   49    5   675  14.21267  202.0     25
2  20    72.0   94   50  1800  14.21267  202.0     25
3  30    77.0   99   55  1925  14.21267  202.0     25

>>> # Custom Stats
>>> custom_stats ={'double_sum': lambda val: val.sum()*2}
>>> custom_stats_df = stats(zones=zones,
                            values=values,
                            stats_funcs=custom_stats)
>>> print(custom_stats_df)
    zone  double_sum
0   0     1100
1  10     1350
2  20     3600
3  30     3850

>>> # Calculate Stats with dask backed xarray DataArrays
>>> dask_stats_df = stats(zones=dask_zones, values=dask_values)
>>> print(type(dask_stats_df))
<class 'dask.dataframe.core.DataFrame'>
>>> print(dask_stats_df.compute())
    zone  mean  max  min   sum       std    var  count
0     0  22.0   44    0   550  14.21267  202.0     25
1    10  27.0   49    5   675  14.21267  202.0     25
2    20  72.0   94   50  1800  14.21267  202.0     25
3    30  77.0   99   55  1925  14.21267  202.0     25

>>> # Custom Stats with dask backed xarray DataArrays
>>> dask_custom_stats ={'double_sum': lambda val: val.sum()*2}
>>> dask_custom_stats_df = stats(
>>>      zones=dask_zones, values=dask_values, stats_funcs=custom_stats
>>> )
>>> print(type(dask_custom_stats_df))
<class 'dask.dataframe.core.DataFrame'>
>>> print(dask_custom_stats_df.compute())
    zone  double_sum
0     0        1100
1    10        1350
2    20        3600
3    30        3850