From 067b2e86e6311e9c37e0def0c83cdb9a1a367a74 Mon Sep 17 00:00:00 2001 From: Benoit Bovy Date: Mon, 21 Mar 2022 05:47:47 +0100 Subject: [PATCH] isel: convert IndexVariable to Variable if index is dropped (#6388) --- xarray/core/dataset.py | 2 ++ xarray/tests/test_dataset.py | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 155cf21b4db..370394909e8 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -2262,6 +2262,8 @@ def _isel_fancy( new_var = var.isel(indexers=var_indexers) else: new_var = var.copy(deep=False) + if name not in indexes: + new_var = new_var.to_base_variable() variables[name] = new_var coord_names = self._coord_names & variables.keys() diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 96fa4ef144e..fe9ec56feea 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -1262,6 +1262,15 @@ def test_isel_dataarray(self): with pytest.raises(IndexError, match=r"dimension coordinate 'dim2'"): actual = data.isel(dim2=indexing_ds["dim2"]) + def test_isel_fancy_convert_index_variable(self) -> None: + # select index variable "x" with a DataArray of dim "z" + # -> drop index and convert index variable to base variable + ds = xr.Dataset({"foo": ("x", [1, 2, 3])}, coords={"x": [0, 1, 2]}) + idxr = xr.DataArray([1], dims="z", name="x") + actual = ds.isel(x=idxr) + assert "x" not in actual.xindexes + assert not isinstance(actual.x.variable, IndexVariable) + def test_sel(self): data = create_test_data() int_slicers = {"dim1": slice(None, None, 2), "dim2": slice(2), "dim3": slice(3)}