From 6a630ad07abb1dbeba7d0f4e043e26f65f1bddb7 Mon Sep 17 00:00:00 2001 From: Matthias Schabel Date: Fri, 25 Sep 2026 01:41:32 -0700 Subject: [PATCH 1/2] Respect drop=True for scalar coordinates an index keeps isel and sel with drop=True promise to drop the scalar coordinates a selection produces. When the selected coordinate belongs to an index whose isel rebuilds the 0-d coordinate itself, isel_indexes returns it among the index variables and the coordinate was silently kept. Drop such coordinates the way drop_vars would, raising the existing corrupt-index error when only some of an index's coordinates would go. The default PandasIndex returns no index for a scalar selection, so its behaviour is unchanged. --- doc/whats-new.rst | 5 ++ xarray/core/dataarray.py | 3 ++ xarray/core/dataset.py | 9 ++++ xarray/core/indexes.py | 25 ++++++++++ xarray/tests/test_dataset.py | 95 +++++++++++++++++++++++++++++++++++- 5 files changed, 136 insertions(+), 1 deletion(-) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index da7259da069..5a87d1aaf65 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -53,6 +53,11 @@ Deprecations Bug Fixes ~~~~~~~~~ +- :py:meth:`Dataset.isel` and :py:meth:`Dataset.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 async zarr tests using ``wraps`` with ``autospec=True`` on async methods, which caused ``AsyncMock`` objects to leak through instead of real array data (:pull:`11232`). diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index 8af786e1e56..ec29bf26dfa 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, ) @@ -1698,6 +1699,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 2706e5eea12..b1edd562b14 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, isel_indexes, remove_unused_levels_categories, @@ -2931,6 +2932,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 @@ -2967,6 +2972,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 ab9b7962020..b21d0f8df76 100644 --- a/xarray/core/indexes.py +++ b/xarray/core/indexes.py @@ -2238,6 +2238,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 3c4c9edcb34..2108c9a861c 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 @@ -44,6 +44,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 from xarray.core.utils import is_scalar from xarray.groupers import SeasonResampler, TimeResampler @@ -96,6 +97,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) @@ -2030,6 +2093,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() From 81a8f22cbc7c0f976e6b9e33cd729bfa4511026a Mon Sep 17 00:00:00 2001 From: Matthias Schabel Date: Thu, 8 Oct 2026 08:22:41 -0700 Subject: [PATCH 2/2] Restore the whats-new entry lost in a merge from main The Bug Fixes entry added with the fix was dropped while resolving a merge from main around the v2026.09.0 release. Re-add it under the unreleased section, naming DataArray as well as Dataset, since both isel paths changed. Co-Authored-By: Claude Opus 5.5 Reviewed-By: Codex (gpt-6-astra, reasoning effort high) --- doc/whats-new.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index fb69f2b4dc5..e51636c878f 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -105,6 +105,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 `_. Documentation