Skip to content

Zonal stats with method='exactextract' not working on flat xarray.Dataarray #131

@maawoo

Description

@maawoo

Here is a reproducible example:

import xarray as xr
import numpy as np
import geopandas as gpd
from shapely.geometry import Point

x_coords = np.arange(500000, 500000 + 100 * 20, 20)
y_coords = np.arange(5500000, 5500000 + 100 * 20, 20)

# dummy Dataarray
test_da = xr.DataArray(
    np.random.random((100, 100)),
    coords={
        'y': y_coords,
        'x': x_coords
    },
    dims=['y', 'x'],
)
# dummy Dataset
test_ds = test_da.to_dataset(name='test_var')

test_gdf = gpd.GeoDataFrame({
    'geometry': [Point(x, y) for x, y in zip(np.random.uniform(x_coords.min(), x_coords.max(), 5), 
                                             np.random.uniform(y_coords.min(), y_coords.max(), 5))]}, 
                                             crs='EPSG:32632')
test_gdf['geometry_buffer'] = test_gdf.geometry.buffer(50)

Using the xarray.Datasetworks:

test_ds.xvec.zonal_stats(
    test_gdf.geometry_buffer, x_coords="x", y_coords="y",
    method='exactextract'
)

Using the xarray.Dataarray doesn't work and raises ValueError: Must pass non-zero number of levels/codes:

test_da.xvec.zonal_stats(
    test_gdf.geometry_buffer, x_coords="x", y_coords="y",
    method='exactextract'
)

arr_dims in the following part is empty when a Dataarray is passed and that results in stack to fail:

xvec/xvec/zonal.py

Lines 699 to 702 in 3ba5d0c

# Stack the other dimensions into one dimension called "location"
arr_dims = tuple(dim for dim in acc._obj.dims if dim not in [x_coords, y_coords])
data = acc._obj.stack(location=arr_dims)
locs = data.location.size

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions