diff --git a/xrspatial/tests/test_zonal.py b/xrspatial/tests/test_zonal.py index 764b1d9a4..9e7655439 100644 --- a/xrspatial/tests/test_zonal.py +++ b/xrspatial/tests/test_zonal.py @@ -2583,6 +2583,15 @@ def test_stats_return_type_invalid_rejected_for_dataset_2558( stats(zones=zones, values=ds, return_type='bogus') +def test_stats_empty_dataset_raises_value_error_2637(small_zones_values_2558): + """An empty Dataset (no data variables) should raise a clear ValueError + instead of leaking an IndexError from the dfs[0] access.""" + zones, _ = small_zones_values_2558 + empty = xr.Dataset() + with pytest.raises(ValueError, match="no data variables"): + stats(zones=zones, values=empty) + + def test_strides_int64_no_overflow_2612(): """`_strides` must accumulate counts in int64, not int32. diff --git a/xrspatial/zonal.py b/xrspatial/zonal.py index 18f864e88..60d63ef63 100644 --- a/xrspatial/zonal.py +++ b/xrspatial/zonal.py @@ -858,6 +858,11 @@ def stats( raise ValueError( "return_type must be 'pandas.DataFrame' when values is a Dataset" ) + if len(values.data_vars) == 0: + raise ValueError( + "values Dataset has no data variables to compute statistics " + "over. Pass a Dataset with at least one data variable." + ) dfs = [] for var_name in values.data_vars: df = stats(