Skip to content

Commit c9d9817

Browse files
Skip nonnumeric variables in Dataset weighted arithmetic (#11833)
* 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 <codex@openai.com> * 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 <codex@openai.com> * 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 <codex@openai.com> * 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 <codex@openai.com> * Simplify Dataset weighted dtype tests Co-authored-by: OpenAI Codex <codex@openai.com> --------- Co-authored-by: OpenAI Codex <codex@openai.com>
1 parent 1196b35 commit c9d9817

3 files changed

Lines changed: 67 additions & 3 deletions

File tree

‎doc/whats-new.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,9 @@ Deprecations
223223

224224
Bug Fixes
225225
~~~~~~~~~
226+
- Dataset weighted arithmetic reductions now select data variables with numeric,
227+
boolean, or timedelta dtypes and skip variables such as datetimes and strings
228+
(:issue:`9322`).
226229
- Weighted variance, standard deviation and sums of squared deviations now
227230
use conjugated deviations for complex data, matching unweighted reductions
228231
and correcting weighted self-correlation.

‎xarray/computation/weighted.py‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@
128128

129129

130130
if TYPE_CHECKING:
131+
from collections.abc import Callable
132+
from typing import Any
133+
131134
from xarray.core.dataarray import DataArray
132135
from xarray.core.dataset import Dataset
133136

@@ -222,7 +225,9 @@ def _reduce(
222225

223226
# `dot` accumulates in the input dtype, so promote bool and small
224227
# integers like `sum` does; else e.g. uint8 weights overflow (GH11867)
225-
dtype = np.result_type(da.dtype, weights.dtype)
228+
data_dtype = getattr(da.dtype, "numpy_dtype", da.dtype)
229+
weights_dtype = getattr(weights.dtype, "numpy_dtype", weights.dtype)
230+
dtype = np.result_type(data_dtype, weights_dtype)
226231
if dtype.kind in "biu" and dtype.itemsize < 8:
227232
dtype = np.dtype(np.uint64 if dtype.kind == "u" else np.int64)
228233
da = da.astype(dtype)
@@ -572,9 +577,20 @@ def _restore_coords(self, dim: Dims, ds: Dataset) -> Dataset:
572577
return ds.assign_coords(self.obj.coords.drop_vars(to_drop))
573578

574579
@override
575-
def _implementation(self, func, dim, **kwargs) -> Dataset:
580+
def _implementation(
581+
self, func: Callable[..., DataArray], dim: Dims, **kwargs: Any
582+
) -> Dataset:
576583
self._check_dim(dim)
577-
result = self.obj.map(func, dim=dim, **kwargs)
584+
dataset = self.obj
585+
# Counting valid weights works for nonnumeric variables too.
586+
if func != self._sum_of_weights:
587+
numeric_vars = [
588+
name
589+
for name, var in dataset.data_vars.items()
590+
if var.dtype.kind in "biufcm"
591+
]
592+
dataset = dataset[numeric_vars]
593+
result = dataset.map(func, dim=dim, **kwargs)
578594
result = self._restore_coords(dim, result)
579595

580596
# Clear attrs when keep_attrs is explicitly False

‎xarray/tests/test_weighted.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from typing import Any
66

77
import numpy as np
8+
import pandas as pd
89
import pytest
910

1011
import xarray as xr
@@ -29,6 +30,50 @@ def test_weighted_non_DataArray_weights(as_dataset: bool) -> None:
2930
data.weighted([1, 2]) # type: ignore[arg-type]
3031

3132

33+
@pytest.mark.parametrize(
34+
("values", "retained"),
35+
(
36+
pytest.param([1.0, 3.0], True, id="float"),
37+
pytest.param(pd.array([1, 3], dtype="Int64"), True, id="nullable-int"),
38+
pytest.param(np.array([1, 3], dtype="timedelta64[ns]"), True, id="timedelta"),
39+
pytest.param(pd.date_range("2000", periods=2), False, id="datetime"),
40+
pytest.param(["a", "b"], False, id="string"),
41+
pytest.param(pd.Categorical(["a", "b"]), False, id="categorical"),
42+
),
43+
)
44+
def test_dataset_weighted_dtype_filter(values: Any, retained: bool) -> None:
45+
ds = Dataset({"numeric": ("x", [1.0, 3.0]), "candidate": ("x", values)})
46+
weights = DataArray([1.0, 2.0], dims="x")
47+
weighted = ds.weighted(weights)
48+
49+
assert_identical(
50+
weighted.sum_of_weights(), Dataset({"numeric": 3.0, "candidate": 3.0})
51+
)
52+
53+
# Quantile also accepts timedeltas, unlike some of the other reductions.
54+
expected = {"numeric", "candidate"} if retained else {"numeric"}
55+
assert set(weighted.quantile(0.5).data_vars) == expected
56+
57+
58+
@pytest.mark.parametrize("as_dataset", (True, False))
59+
def test_weighted_nullable_data_and_weights(as_dataset: bool) -> None:
60+
data: DataArray | Dataset = DataArray(
61+
pd.array([100, 200], dtype="Int64"), dims="x", name="values"
62+
)
63+
weights = DataArray(pd.array([True, True], dtype="boolean"), dims="x")
64+
if as_dataset:
65+
data = data.to_dataset()
66+
67+
expected_sum: DataArray | Dataset = DataArray(300, name="values")
68+
expected_mean: DataArray | Dataset = DataArray(150, name="values")
69+
if as_dataset:
70+
expected_sum = expected_sum.to_dataset()
71+
expected_mean = expected_mean.to_dataset()
72+
73+
assert_equal(data.weighted(weights).sum(), expected_sum)
74+
assert_equal(data.weighted(weights).mean(), expected_mean)
75+
76+
3277
@pytest.mark.parametrize("as_dataset", (True, False))
3378
@pytest.mark.parametrize("weights", ([np.nan, 2], [np.nan, np.nan]))
3479
def test_weighted_weights_nan_raises(as_dataset: bool, weights: list[float]) -> None:

0 commit comments

Comments
 (0)