Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ Deprecations

Bug Fixes
~~~~~~~~~
- Dataset weighted arithmetic reductions now select data variables with numeric,
boolean, or timedelta dtypes and skip variables such as datetimes and strings
(:issue:`9322`).
- Weighted variance, standard deviation and sums of squared deviations now
use conjugated deviations for complex data, matching unweighted reductions
and correcting weighted self-correlation.
Expand Down
22 changes: 19 additions & 3 deletions xarray/computation/weighted.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,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

Expand Down Expand Up @@ -222,7 +225,9 @@ def _reduce(

# `dot` accumulates in the input dtype, so promote bool and small
# integers like `sum` does; else e.g. uint8 weights overflow (GH11867)
dtype = np.result_type(da.dtype, weights.dtype)
data_dtype = getattr(da.dtype, "numpy_dtype", da.dtype)
weights_dtype = getattr(weights.dtype, "numpy_dtype", weights.dtype)
dtype = np.result_type(data_dtype, weights_dtype)
if dtype.kind in "biu" and dtype.itemsize < 8:
dtype = np.dtype(np.uint64 if dtype.kind == "u" else np.int64)
da = da.astype(dtype)
Expand Down Expand Up @@ -572,9 +577,20 @@ 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 dataset.data_vars.items()
if var.dtype.kind in "biufcm"
]
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
Expand Down
45 changes: 45 additions & 0 deletions xarray/tests/test_weighted.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import Any

import numpy as np
import pandas as pd
import pytest

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


@pytest.mark.parametrize(
("values", "retained"),
(
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_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)

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))
def test_weighted_nullable_data_and_weights(as_dataset: bool) -> None:
data: DataArray | Dataset = DataArray(
pd.array([100, 200], dtype="Int64"), dims="x", name="values"
)
weights = DataArray(pd.array([True, True], dtype="boolean"), dims="x")
if as_dataset:
data = data.to_dataset()

expected_sum: DataArray | Dataset = DataArray(300, name="values")
expected_mean: DataArray | Dataset = DataArray(150, name="values")
if as_dataset:
expected_sum = expected_sum.to_dataset()
expected_mean = expected_mean.to_dataset()

assert_equal(data.weighted(weights).sum(), expected_sum)
assert_equal(data.weighted(weights).mean(), expected_mean)


@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:
Expand Down
Loading