From f0d588dd24147339ad07385a70dde7cdd6ab74c6 Mon Sep 17 00:00:00 2001 From: KanishqGandharv219 <133373835+KanishqGandharv219@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:27:29 +0000 Subject: [PATCH 1/5] Skip nonnumeric variables in Dataset weighted arithmetic Filter nonnumeric data variables before weighted arithmetic reductions while preserving the existing sum_of_weights count scope and lazy Dask behavior. Add NumPy and Dask regressions and document the change. Co-authored-by: OpenAI Codex --- doc/whats-new.rst | 2 + xarray/computation/weighted.py | 23 +++++- xarray/tests/test_weighted.py | 127 +++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+), 2 deletions(-) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 65551d3a2f4..de88469a828 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -211,6 +211,8 @@ Deprecations Bug Fixes ~~~~~~~~~ +- Dataset weighted arithmetic reductions now skip nonnumeric data variables + (:issue:`9322`). - Fix CuPy indexers with pandas-backed coordinates, basic and label-based assignment to CuPy arrays, and scalar truth conversion (:issue:`11739`, :pull:`11797`). diff --git a/xarray/computation/weighted.py b/xarray/computation/weighted.py index 3d8e9af488f..990896ad56b 100644 --- a/xarray/computation/weighted.py +++ b/xarray/computation/weighted.py @@ -9,6 +9,7 @@ from xarray.computation.apply_ufunc import apply_ufunc from xarray.computation.computation import dot from xarray.core import duck_array_ops, utils +from xarray.core.common import _is_numeric_aggregatable_dtype from xarray.core.types import Dims, T_DataArray, T_Xarray from xarray.namedarray.utils import is_duck_dask_array from xarray.structure.alignment import align, broadcast @@ -128,6 +129,9 @@ if TYPE_CHECKING: + from collections.abc import Callable + from typing import Any + from xarray.core.dataarray import DataArray from xarray.core.dataset import Dataset @@ -561,9 +565,24 @@ def _restore_coords(self, dim: Dims, ds: Dataset) -> Dataset: return ds.assign_coords(self.obj.coords.drop_vars(to_drop)) @override - def _implementation(self, func, dim, **kwargs) -> Dataset: + def _implementation( + self, func: Callable[..., DataArray], dim: Dims, **kwargs: Any + ) -> Dataset: self._check_dim(dim) - result = self.obj.map(func, dim=dim, **kwargs) + dataset = self.obj + # Counting valid weights works for nonnumeric variables too. + if func != self._sum_of_weights: + numeric_vars = [ + name + for name, var in self.obj.data_vars.items() + if var.dtype.kind in "biufcmM" + or ( + not utils.is_allowed_extension_array_dtype(var.dtype) + and _is_numeric_aggregatable_dtype(var.variable) + ) + ] + dataset = dataset[numeric_vars] + result = dataset.map(func, dim=dim, **kwargs) result = self._restore_coords(dim, result) # Clear attrs when keep_attrs is explicitly False diff --git a/xarray/tests/test_weighted.py b/xarray/tests/test_weighted.py index 345d8d7d0c9..7c00632f6d7 100644 --- a/xarray/tests/test_weighted.py +++ b/xarray/tests/test_weighted.py @@ -5,6 +5,7 @@ from typing import Any import numpy as np +import pandas as pd import pytest import xarray as xr @@ -29,6 +30,132 @@ def test_weighted_non_DataArray_weights(as_dataset: bool) -> None: data.weighted([1, 2]) # type: ignore[arg-type] +@pytest.mark.parametrize( + "operation", + ("sum_of_weights", "sum", "mean", "sum_of_squares", "var", "std", "quantile"), +) +@pytest.mark.parametrize("include_numeric", (True, False)) +def test_dataset_weighted_non_numeric( + operation: str, include_numeric: bool, use_dask: bool +) -> None: + data = Dataset( + { + "text": ("x", ["a", "b"]), + "bytes": ("x", [b"a", b"b"]), + "objects": ("x", np.array(["a", None], dtype=object)), + }, + coords={"x": [0, 1], "label": ("other", ["p", "q"]), "scalar": 42}, + attrs={"description": "mixed dataset"}, + ) + numeric = DataArray([1.0, 3.0], dims="x", coords={"x": [0, 1]}) + if include_numeric: + data["numeric"] = numeric + weights = DataArray([1.0, 2.0], dims="x", coords={"x": [0, 1]}) + if use_dask: + data = data.chunk({"x": -1}) + weights = weights.chunk({"x": -1}) + original = data.copy(deep=True) + kwargs: dict[str, Any] = {"dim": "x", "keep_attrs": True} + if operation == "quantile": + kwargs["q"] = 0.5 + + result = getattr(data.weighted(weights), operation)(**kwargs) + + expected = Dataset( + coords={"label": ("other", ["p", "q"]), "scalar": 42}, attrs=data.attrs + ) + if include_numeric: + expected["numeric"] = getattr(numeric.weighted(weights), operation)(**kwargs) + if operation == "sum_of_weights": + expected = expected.assign(text=3.0, bytes=3.0, objects=1.0) + assert_identical(result, expected) + assert_identical(data, original) + + +@pytest.mark.parametrize("operation", ("sum_of_weights", "sum", "mean")) +@pytest.mark.parametrize( + "values", + ( + np.array(["2000-01-01", "2000-01-02"], dtype="datetime64[ns]"), + np.array([1, 3], dtype="timedelta64[ns]"), + pd.array([1, 3], dtype="Int64"), + ), +) +def test_dataset_weighted_retains_aggregatable_dtypes( + values: Any, operation: str +) -> None: + data = DataArray(values, dims="x", name="data") + weights = DataArray([1.0, 2.0], dims="x") + + result = getattr(data.to_dataset().weighted(weights), operation)() + expected = getattr(data.weighted(weights), operation)().to_dataset() + + assert_identical(result, expected) + + +def test_dataset_weighted_timedelta_quantile(use_dask: bool) -> None: + data = Dataset({"duration": ("x", np.array([1, 3], dtype="timedelta64[ns]"))}) + if use_dask: + data = data.chunk({"x": -1}) + weights = DataArray([1.0, 2.0], dims="x") + + result = data.weighted(weights).quantile(0.5) + + expected = Dataset({"duration": 2.0}, coords={"quantile": 0.5}) + assert_identical(result, expected) + + +@requires_cftime +def test_dataset_weighted_cftime_sum_of_weights() -> None: + data = DataArray( + xr.date_range("2000", periods=2, use_cftime=True), dims="x", name="dates" + ) + weights = DataArray([1.0, 2.0], dims="x") + + result = data.to_dataset().weighted(weights).sum_of_weights() + + assert_identical(result, Dataset({"dates": 3.0})) + + +@requires_cftime +def test_dataset_weighted_cftime_missing_first_sum_of_weights(use_dask: bool) -> None: + date = xr.date_range("2000", periods=1, use_cftime=True)[0] + data = Dataset({"dates": ("x", [None, date])}) + if use_dask: + data = data.chunk({"x": 1}) + weights = DataArray([1.0, 2.0], dims="x") + + result = data.weighted(weights).sum_of_weights() + + expected = data["dates"].weighted(weights).sum_of_weights().to_dataset() + assert_identical(result, expected) + if not use_dask: + assert_identical(result, Dataset({"dates": 2.0})) + + +@requires_cftime +@requires_dask +def test_dataset_weighted_cftime_sum_of_weights_lazy() -> None: + data = Dataset( + {"dates": ("x", xr.date_range("2000", periods=2, use_cftime=True))} + ).chunk({"x": 1}) + weights = DataArray([1.0, 2.0], dims="x") + + with raise_if_dask_computes(): + result = data.weighted(weights).sum_of_weights() + + assert_identical(result, Dataset({"dates": 3.0})) + + +def test_dataset_weighted_timezone_sum_of_weights() -> None: + data = DataArray(pd.date_range("2000", periods=2, tz="UTC"), dims="x", name="dates") + weights = DataArray([1.0, 2.0], dims="x") + + result = data.to_dataset().weighted(weights).sum_of_weights() + + assert_identical(result, Dataset({"dates": 3.0})) + + @pytest.mark.parametrize("as_dataset", (True, False)) @pytest.mark.parametrize("weights", ([np.nan, 2], [np.nan, np.nan])) def test_weighted_weights_nan_raises(as_dataset: bool, weights: list[float]) -> None: From 18fc1fc50bf7d6c702ea95d1d510a6bb431bba39 Mon Sep 17 00:00:00 2001 From: KanishqGandharv219 <133373835+KanishqGandharv219@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:49:29 +0000 Subject: [PATCH 2/5] Check weighted dtype compatibility with either einsum backend Compare Dataset weighted results or dtype-promotion errors with DataArray under both use_opt_einsum settings. This preserves coverage of supported counts and arithmetic without assuming the optional backend is installed. Co-authored-by: OpenAI Codex --- xarray/tests/test_weighted.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/xarray/tests/test_weighted.py b/xarray/tests/test_weighted.py index 7c00632f6d7..b467311ec93 100644 --- a/xarray/tests/test_weighted.py +++ b/xarray/tests/test_weighted.py @@ -73,6 +73,7 @@ def test_dataset_weighted_non_numeric( @pytest.mark.parametrize("operation", ("sum_of_weights", "sum", "mean")) +@pytest.mark.parametrize("use_opt_einsum", (False, True)) @pytest.mark.parametrize( "values", ( @@ -82,15 +83,21 @@ def test_dataset_weighted_non_numeric( ), ) def test_dataset_weighted_retains_aggregatable_dtypes( - values: Any, operation: str + values: Any, operation: str, use_opt_einsum: bool ) -> None: data = DataArray(values, dims="x", name="data") weights = DataArray([1.0, 2.0], dims="x") - result = getattr(data.to_dataset().weighted(weights), operation)() - expected = getattr(data.weighted(weights), operation)().to_dataset() - - assert_identical(result, expected) + with xr.set_options(use_opt_einsum=use_opt_einsum): + try: + expected = getattr(data.weighted(weights), operation)().to_dataset() + except np.exceptions.DTypePromotionError as expected_error: + with pytest.raises(np.exceptions.DTypePromotionError) as actual_error: + getattr(data.to_dataset().weighted(weights), operation)() + assert str(actual_error.value) == str(expected_error) + else: + result = getattr(data.to_dataset().weighted(weights), operation)() + assert_identical(result, expected) def test_dataset_weighted_timedelta_quantile(use_dask: bool) -> None: From 9b21f522b60fd304ccb56ce202bcf11bbbdbf232 Mon Sep 17 00:00:00 2001 From: Kanishq Gandharv <133373835+KanishqGandharv219@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:09:41 +0000 Subject: [PATCH 3/5] Preserve backend-specific object counts in weighted tests Compare Dask object counts with unchanged DataArray behavior while keeping the explicit NumPy expectation. This preserves coverage without assuming the newer Dask null handling in the minimum-version environment. Co-authored-by: OpenAI Codex --- xarray/tests/test_weighted.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/xarray/tests/test_weighted.py b/xarray/tests/test_weighted.py index b467311ec93..a9c9e8cc5f1 100644 --- a/xarray/tests/test_weighted.py +++ b/xarray/tests/test_weighted.py @@ -67,7 +67,15 @@ def test_dataset_weighted_non_numeric( if include_numeric: expected["numeric"] = getattr(numeric.weighted(weights), operation)(**kwargs) if operation == "sum_of_weights": - expected = expected.assign(text=3.0, bytes=3.0, objects=1.0) + expected = expected.assign( + text=3.0, + bytes=3.0, + objects=( + data["objects"].weighted(weights).sum_of_weights(**kwargs) + if use_dask + else 1.0 + ), + ) assert_identical(result, expected) assert_identical(data, original) From ee20db2ca65624e48f7423ce5fe53e65164df0d8 Mon Sep 17 00:00:00 2001 From: KanishqGandharv219 Date: Mon, 16 Nov 2026 09:04:27 +0000 Subject: [PATCH 4/5] Select Dataset weighted variables by dtype kind Skip datetime and object variables for weighted arithmetic without reading their data. Keep all variables eligible for sum_of_weights. Co-authored-by: OpenAI Codex --- doc/whats-new.rst | 3 ++- xarray/computation/weighted.py | 9 ++------ xarray/tests/test_weighted.py | 41 ++++++++++++++++++++-------------- 3 files changed, 28 insertions(+), 25 deletions(-) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 1849f526799..18fe08e484e 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -219,7 +219,8 @@ Deprecations Bug Fixes ~~~~~~~~~ -- Dataset weighted arithmetic reductions now skip nonnumeric data variables +- Dataset weighted arithmetic reductions now select data variables with numeric, + boolean, or timedelta dtypes and skip variables such as datetimes and strings (:issue:`9322`). - The HTML representation of a :py:class:`Dataset` no longer fails when a data variable has non-string dimension names, e.g. tuples (:issue:`10613`). diff --git a/xarray/computation/weighted.py b/xarray/computation/weighted.py index 990896ad56b..817cb4781b5 100644 --- a/xarray/computation/weighted.py +++ b/xarray/computation/weighted.py @@ -9,7 +9,6 @@ from xarray.computation.apply_ufunc import apply_ufunc from xarray.computation.computation import dot from xarray.core import duck_array_ops, utils -from xarray.core.common import _is_numeric_aggregatable_dtype from xarray.core.types import Dims, T_DataArray, T_Xarray from xarray.namedarray.utils import is_duck_dask_array from xarray.structure.alignment import align, broadcast @@ -574,12 +573,8 @@ def _implementation( if func != self._sum_of_weights: numeric_vars = [ name - for name, var in self.obj.data_vars.items() - if var.dtype.kind in "biufcmM" - or ( - not utils.is_allowed_extension_array_dtype(var.dtype) - and _is_numeric_aggregatable_dtype(var.variable) - ) + for name, var in dataset.data_vars.items() + if var.dtype.kind in "biufcm" ] dataset = dataset[numeric_vars] result = dataset.map(func, dim=dim, **kwargs) diff --git a/xarray/tests/test_weighted.py b/xarray/tests/test_weighted.py index a9c9e8cc5f1..b324f53a335 100644 --- a/xarray/tests/test_weighted.py +++ b/xarray/tests/test_weighted.py @@ -43,6 +43,8 @@ def test_dataset_weighted_non_numeric( "text": ("x", ["a", "b"]), "bytes": ("x", [b"a", b"b"]), "objects": ("x", np.array(["a", None], dtype=object)), + "object_numbers": ("x", np.array([1, 3], dtype=object)), + "dates": ("x", pd.date_range("2000", periods=2)), }, coords={"x": [0, 1], "label": ("other", ["p", "q"]), "scalar": 42}, attrs={"description": "mixed dataset"}, @@ -70,6 +72,8 @@ def test_dataset_weighted_non_numeric( expected = expected.assign( text=3.0, bytes=3.0, + object_numbers=3.0, + dates=3.0, objects=( data["objects"].weighted(weights).sum_of_weights(**kwargs) if use_dask @@ -85,7 +89,6 @@ def test_dataset_weighted_non_numeric( @pytest.mark.parametrize( "values", ( - np.array(["2000-01-01", "2000-01-02"], dtype="datetime64[ns]"), np.array([1, 3], dtype="timedelta64[ns]"), pd.array([1, 3], dtype="Int64"), ), @@ -120,18 +123,6 @@ def test_dataset_weighted_timedelta_quantile(use_dask: bool) -> None: assert_identical(result, expected) -@requires_cftime -def test_dataset_weighted_cftime_sum_of_weights() -> None: - data = DataArray( - xr.date_range("2000", periods=2, use_cftime=True), dims="x", name="dates" - ) - weights = DataArray([1.0, 2.0], dims="x") - - result = data.to_dataset().weighted(weights).sum_of_weights() - - assert_identical(result, Dataset({"dates": 3.0})) - - @requires_cftime def test_dataset_weighted_cftime_missing_first_sum_of_weights(use_dask: bool) -> None: date = xr.date_range("2000", periods=1, use_cftime=True)[0] @@ -150,16 +141,32 @@ def test_dataset_weighted_cftime_missing_first_sum_of_weights(use_dask: bool) -> @requires_cftime @requires_dask -def test_dataset_weighted_cftime_sum_of_weights_lazy() -> None: +@pytest.mark.parametrize("operation", ("mean", "sum_of_weights")) +def test_dataset_weighted_cftime_lazy(operation: str) -> None: data = Dataset( - {"dates": ("x", xr.date_range("2000", periods=2, use_cftime=True))} + { + "dates": ("x", xr.date_range("2000", periods=2, use_cftime=True)), + "numeric": ("x", [1, 4]), + } ).chunk({"x": 1}) weights = DataArray([1.0, 2.0], dims="x") with raise_if_dask_computes(): - result = data.weighted(weights).sum_of_weights() + result = getattr(data.weighted(weights), operation)() - assert_identical(result, Dataset({"dates": 3.0})) + expected = ( + Dataset({"numeric": 3.0}) + if operation == "mean" + else Dataset({"numeric": 3.0, "dates": 3.0}) + ) + assert_identical(result, expected) + + +def test_dataset_weighted_categorical() -> None: + data = Dataset({"value": ("x", [1, 3]), "label": ("x", pd.Categorical(["a", "b"]))}) + weights = DataArray([1, 1], dims="x") + + assert_identical(data.weighted(weights).mean(), Dataset({"value": 2.0})) def test_dataset_weighted_timezone_sum_of_weights() -> None: From 36a7c593d654f7f636bc8d76d3152f260c0579cf Mon Sep 17 00:00:00 2001 From: KanishqGandharv219 Date: Mon, 23 Nov 2026 10:25:08 +0000 Subject: [PATCH 5/5] Simplify Dataset weighted dtype tests Co-authored-by: OpenAI Codex --- xarray/tests/test_weighted.py | 157 ++++------------------------------ 1 file changed, 17 insertions(+), 140 deletions(-) diff --git a/xarray/tests/test_weighted.py b/xarray/tests/test_weighted.py index cfc6bb0a5ba..e221233a7a9 100644 --- a/xarray/tests/test_weighted.py +++ b/xarray/tests/test_weighted.py @@ -31,84 +31,28 @@ def test_weighted_non_DataArray_weights(as_dataset: bool) -> None: @pytest.mark.parametrize( - "operation", - ("sum_of_weights", "sum", "mean", "sum_of_squares", "var", "std", "quantile"), -) -@pytest.mark.parametrize("include_numeric", (True, False)) -def test_dataset_weighted_non_numeric( - operation: str, include_numeric: bool, use_dask: bool -) -> None: - data = Dataset( - { - "text": ("x", ["a", "b"]), - "bytes": ("x", [b"a", b"b"]), - "objects": ("x", np.array(["a", None], dtype=object)), - "object_numbers": ("x", np.array([1, 3], dtype=object)), - "dates": ("x", pd.date_range("2000", periods=2)), - }, - coords={"x": [0, 1], "label": ("other", ["p", "q"]), "scalar": 42}, - attrs={"description": "mixed dataset"}, - ) - numeric = DataArray([1.0, 3.0], dims="x", coords={"x": [0, 1]}) - if include_numeric: - data["numeric"] = numeric - weights = DataArray([1.0, 2.0], dims="x", coords={"x": [0, 1]}) - if use_dask: - data = data.chunk({"x": -1}) - weights = weights.chunk({"x": -1}) - original = data.copy(deep=True) - kwargs: dict[str, Any] = {"dim": "x", "keep_attrs": True} - if operation == "quantile": - kwargs["q"] = 0.5 - - result = getattr(data.weighted(weights), operation)(**kwargs) - - expected = Dataset( - coords={"label": ("other", ["p", "q"]), "scalar": 42}, attrs=data.attrs - ) - if include_numeric: - expected["numeric"] = getattr(numeric.weighted(weights), operation)(**kwargs) - if operation == "sum_of_weights": - expected = expected.assign( - text=3.0, - bytes=3.0, - object_numbers=3.0, - dates=3.0, - objects=( - data["objects"].weighted(weights).sum_of_weights(**kwargs) - if use_dask - else 1.0 - ), - ) - assert_identical(result, expected) - assert_identical(data, original) - - -@pytest.mark.parametrize("operation", ("sum_of_weights", "sum", "mean")) -@pytest.mark.parametrize("use_opt_einsum", (False, True)) -@pytest.mark.parametrize( - "values", + ("values", "retained"), ( - np.array([1, 3], dtype="timedelta64[ns]"), - pd.array([1, 3], dtype="Int64"), + pytest.param([1.0, 3.0], True, id="float"), + pytest.param(pd.array([1, 3], dtype="Int64"), True, id="nullable-int"), + pytest.param(np.array([1, 3], dtype="timedelta64[ns]"), True, id="timedelta"), + pytest.param(pd.date_range("2000", periods=2), False, id="datetime"), + pytest.param(["a", "b"], False, id="string"), + pytest.param(pd.Categorical(["a", "b"]), False, id="categorical"), ), ) -def test_dataset_weighted_retains_aggregatable_dtypes( - values: Any, operation: str, use_opt_einsum: bool -) -> None: - data = DataArray(values, dims="x", name="data") +def test_dataset_weighted_dtype_filter(values: Any, retained: bool) -> None: + ds = Dataset({"numeric": ("x", [1.0, 3.0]), "candidate": ("x", values)}) weights = DataArray([1.0, 2.0], dims="x") + weighted = ds.weighted(weights) - with xr.set_options(use_opt_einsum=use_opt_einsum): - try: - expected = getattr(data.weighted(weights), operation)().to_dataset() - except np.exceptions.DTypePromotionError as expected_error: - with pytest.raises(np.exceptions.DTypePromotionError) as actual_error: - getattr(data.to_dataset().weighted(weights), operation)() - assert str(actual_error.value) == str(expected_error) - else: - result = getattr(data.to_dataset().weighted(weights), operation)() - assert_identical(result, expected) + assert_identical( + weighted.sum_of_weights(), Dataset({"numeric": 3.0, "candidate": 3.0}) + ) + + # Quantile also accepts timedeltas, unlike some of the other reductions. + expected = {"numeric", "candidate"} if retained else {"numeric"} + assert set(weighted.quantile(0.5).data_vars) == expected @pytest.mark.parametrize("as_dataset", (True, False)) @@ -130,73 +74,6 @@ def test_weighted_nullable_data_and_weights(as_dataset: bool) -> None: assert_equal(data.weighted(weights).mean(), expected_mean) -def test_dataset_weighted_timedelta_quantile(use_dask: bool) -> None: - data = Dataset({"duration": ("x", np.array([1, 3], dtype="timedelta64[ns]"))}) - if use_dask: - data = data.chunk({"x": -1}) - weights = DataArray([1.0, 2.0], dims="x") - - result = data.weighted(weights).quantile(0.5) - - expected = Dataset({"duration": 2.0}, coords={"quantile": 0.5}) - assert_identical(result, expected) - - -@requires_cftime -def test_dataset_weighted_cftime_missing_first_sum_of_weights(use_dask: bool) -> None: - date = xr.date_range("2000", periods=1, use_cftime=True)[0] - data = Dataset({"dates": ("x", [None, date])}) - if use_dask: - data = data.chunk({"x": 1}) - weights = DataArray([1.0, 2.0], dims="x") - - result = data.weighted(weights).sum_of_weights() - - expected = data["dates"].weighted(weights).sum_of_weights().to_dataset() - assert_identical(result, expected) - if not use_dask: - assert_identical(result, Dataset({"dates": 2.0})) - - -@requires_cftime -@requires_dask -@pytest.mark.parametrize("operation", ("mean", "sum_of_weights")) -def test_dataset_weighted_cftime_lazy(operation: str) -> None: - data = Dataset( - { - "dates": ("x", xr.date_range("2000", periods=2, use_cftime=True)), - "numeric": ("x", [1, 4]), - } - ).chunk({"x": 1}) - weights = DataArray([1.0, 2.0], dims="x") - - with raise_if_dask_computes(): - result = getattr(data.weighted(weights), operation)() - - expected = ( - Dataset({"numeric": 3.0}) - if operation == "mean" - else Dataset({"numeric": 3.0, "dates": 3.0}) - ) - assert_identical(result, expected) - - -def test_dataset_weighted_categorical() -> None: - data = Dataset({"value": ("x", [1, 3]), "label": ("x", pd.Categorical(["a", "b"]))}) - weights = DataArray([1, 1], dims="x") - - assert_identical(data.weighted(weights).mean(), Dataset({"value": 2.0})) - - -def test_dataset_weighted_timezone_sum_of_weights() -> None: - data = DataArray(pd.date_range("2000", periods=2, tz="UTC"), dims="x", name="dates") - weights = DataArray([1.0, 2.0], dims="x") - - result = data.to_dataset().weighted(weights).sum_of_weights() - - assert_identical(result, Dataset({"dates": 3.0})) - - @pytest.mark.parametrize("as_dataset", (True, False)) @pytest.mark.parametrize("weights", ([np.nan, 2], [np.nan, np.nan])) def test_weighted_weights_nan_raises(as_dataset: bool, weights: list[float]) -> None: