diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 5b815ec6881..b82893e93a5 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -415,6 +415,11 @@ Bug Fixes This was due to a bug in the reduction method generation introduced in :pull:`11556` (:pull:`11686`). By `Andrew Scherer `_. +- :py:meth:`Dataset.isel`, :py:meth:`Dataset.sel`, :py:meth:`DataArray.isel` and + :py:meth:`DataArray.sel` now honor ``drop=True`` when a custom index preserves + selected coordinates as scalars. They now raise when only some of an index's + coordinates would be dropped, instead of silently keeping them (:pull:`11617`). + By `Matthias Schabel `_. - Fix the ``preferred_chunks`` encoding of sharded Zarr variables read with :py:func:`open_zarr`: it now holds the shard (outer/storage chunk) sizes instead of the inner chunk sizes, so the default dask chunks align with the diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index 6fd4773dc01..6d94bbfcb79 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -36,6 +36,7 @@ Index, Indexes, PandasMultiIndex, + drop_scalar_index_coords, filter_indexes_from_coords, isel_indexes, ) @@ -1795,6 +1796,8 @@ def isel( variable = self._variable.isel(indexers, missing_dims=missing_dims) indexes, index_variables = isel_indexes(self.xindexes, indexers) + if drop: + drop_scalar_index_coords(indexes, index_variables, self._coords, indexers) coords = {} for coord_name, coord_value in self._coords.items(): diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index eed51459204..17a8cfa99a9 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -65,6 +65,7 @@ PandasMultiIndex, assert_no_index_corrupted, create_default_index_implicit, + drop_scalar_index_coords, filter_indexes_from_coords, is_full_ordered_product, isel_indexes, @@ -2984,6 +2985,10 @@ def isel( coord_names = self._coord_names.copy() indexes, index_variables = isel_indexes(self.xindexes, indexers) + if drop: + drop_scalar_index_coords( + indexes, index_variables, self._variables, indexers + ) for name, var in self._variables.items(): # preserve variable order @@ -3020,6 +3025,10 @@ def _isel_fancy( variables: dict[Hashable, Variable] = {} indexes, index_variables = isel_indexes(self.xindexes, valid_indexers) + if drop: + drop_scalar_index_coords( + indexes, index_variables, self._variables, valid_indexers + ) for name, var in self.variables.items(): if name in index_variables: diff --git a/xarray/core/indexes.py b/xarray/core/indexes.py index d739feb2640..6af55f96ce4 100644 --- a/xarray/core/indexes.py +++ b/xarray/core/indexes.py @@ -2287,6 +2287,31 @@ def isel_indexes( return _apply_indexes_fast(indexes, indexers, "isel") +def drop_scalar_index_coords( + indexes: dict[Hashable, Index], + index_variables: dict[Hashable, Variable], + coordinates: Mapping[Hashable, Variable], + indexers: Mapping[Hashable, Any], +) -> None: + """Drop scalar coordinates rebuilt by indexes, rejecting partial drops.""" + drop_names = { + name + for name, var in index_variables.items() + if name in coordinates + and coordinates[name].ndim > 0 + and set(coordinates[name].dims) & set(indexers) + and var.ndim == 0 + } + if drop_names: + assert_no_index_corrupted( + Indexes({k: indexes[k] for k in index_variables}, index_variables), + drop_names, + ) + for name in drop_names: + del indexes[name] + del index_variables[name] + + def roll_indexes( indexes: Indexes[Index], shifts: Mapping[Any, int], diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 6514b30293d..43af935c676 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -4,7 +4,7 @@ import re import sys import warnings -from collections.abc import Hashable +from collections.abc import Hashable, Mapping from copy import copy, deepcopy from io import StringIO from textwrap import dedent @@ -37,6 +37,7 @@ from xarray.core.common import duck_array_ops, full_like from xarray.core.coordinates import Coordinates, DatasetCoordinates from xarray.core.indexes import Index, PandasIndex +from xarray.core.indexing import IndexSelResult from xarray.core.types import ArrayLike, QueryEngineOptions, QueryParserOptions from xarray.core.utils import is_scalar from xarray.groupers import SeasonResampler, TimeResampler @@ -78,6 +79,68 @@ ] +class ScalarPreservingIndex(Index): + def __init__( + self, + axes: Mapping[Hashable, PandasIndex], + scalars: Mapping[Hashable, Variable] | None = None, + ) -> None: + self.axes = dict(axes) + self.scalars = dict(scalars or {}) + + @classmethod + def from_variables( + cls, variables: Mapping[Hashable, Variable], *, options: Mapping[str, Any] + ) -> ScalarPreservingIndex: + return cls( + { + name: PandasIndex.from_variables({name: var}, options={}) + for name, var in variables.items() + } + ) + + def create_variables( + self, variables: Mapping[Hashable, Variable] | None = None + ) -> dict[Hashable, Variable]: + result = dict(self.scalars) + for name, axis in self.axes.items(): + source = ( + {name: variables[name]} if variables and name in variables else None + ) + result.update(axis.create_variables(source)) + return result + + def isel(self, indexers: Mapping[Hashable, Any]) -> ScalarPreservingIndex: + axes = {} + scalars = dict(self.scalars) + for name, axis in self.axes.items(): + if axis.dim in indexers: + reduced = axis.isel({axis.dim: indexers[axis.dim]}) + if reduced is None: + position = np.asarray(indexers[axis.dim]).item() + scalars[name] = Variable((), axis.index[position]) + else: + axes[name] = reduced + else: + axes[name] = axis + return type(self)(axes, scalars) + + def sel(self, labels: dict[Hashable, Any]) -> IndexSelResult: + indexers = {} + for name, label in labels.items(): + indexers.update(self.axes[name].sel({name: label}).dim_indexers) + return IndexSelResult(indexers) + + +def create_scalar_preserving_array() -> DataArray: + array = DataArray( + np.arange(6).reshape(2, 3), + dims=("y", "x"), + coords={"y": [0, 1], "x": [10, 20, 30]}, + ) + return array.drop_indexes(["y", "x"]).set_xindex(["y", "x"], ScalarPreservingIndex) + + def create_append_test_data(seed=None) -> tuple[Dataset, Dataset, Dataset]: rs = np.random.default_rng(seed) @@ -2015,6 +2078,36 @@ def test_isel_drop(self) -> None: selected = data.isel(x=0, drop=False) assert_identical(expected, selected) + @pytest.mark.parametrize("method", ["isel", "sel"]) + @pytest.mark.parametrize("as_dataset", [False, True]) + def test_drop_scalar_coordinate_rejects_partial_index_drop( + self, method: str, as_dataset: bool + ) -> None: + array = create_scalar_preserving_array() + obj = array.to_dataset(name="data") if as_dataset else array + + with pytest.raises(ValueError, match="would corrupt the following index"): + getattr(obj, method)(x=0 if method == "isel" else 10, drop=True) + + @pytest.mark.parametrize("as_dataset", [False, True]) + @pytest.mark.parametrize("indexer", [0, DataArray(0)]) + @pytest.mark.parametrize("extra_index", [False, True]) + def test_drop_all_scalar_index_coordinates( + self, as_dataset: bool, indexer: int | DataArray, extra_index: bool + ) -> None: + array = create_scalar_preserving_array() + if extra_index: + array = array.expand_dims(z=[0, 1]) + obj = array.to_dataset(name="data") if as_dataset else array + + result = obj.isel(x=indexer, y=0, drop=True) + expected_coords = {"z"} if extra_index else set() + assert set(result.coords) == expected_coords + assert set(result.xindexes) == expected_coords + if extra_index: + assert_identical(result["z"], obj["z"]) + assert isinstance(result.xindexes["z"], PandasIndex) + def test_head(self) -> None: data = create_test_data()