diff --git a/doc/whats-new.rst b/doc/whats-new.rst index fe78d86f8be..8929f604088 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -41,6 +41,8 @@ Bug Fixes By `Ian Hunt-Isaak `_. - Always normalize slices when indexing ``LazilyIndexedArray`` instances (:issue:`10941`, :pull:`10948`). By `Justus Magin `_. +- Avoid casting custom indexes in ``Dataset.drop_attrs`` (:pull:`10961`) + By `Justus Magin `_. Documentation ~~~~~~~~~~~~~ diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 9c2c2f60db1..bce048048da 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -10475,7 +10475,7 @@ def drop_attrs(self, *, deep: bool = True) -> Self: for var in self.variables: # variables don't have a `._replace` method, so we copy and then remove # attrs. If we added a `._replace` method, we could use that instead. - if var not in self.indexes: + if var not in self.xindexes: self[var] = self[var].copy() self[var].attrs = {} diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index e677430dfbf..bf2e8f6cb8c 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -4868,6 +4868,19 @@ def test_drop_attrs(self) -> None: assert list(result.data_vars) == list(ds.data_vars) assert list(result.coords) == list(ds.coords) + def test_drop_attrs_custom_index(self): + class CustomIndex(Index): + @classmethod + def from_variables(cls, variables, *, options=None): + return cls() + + ds = xr.Dataset(coords={"y": ("x", [1, 2])}).set_xindex("y", CustomIndex) + # should not raise a TypeError + ds.drop_attrs() + + # make sure the index didn't disappear + assert "y" in ds.xindexes + def test_assign_multiindex_level(self) -> None: data = create_test_multiindex() with pytest.raises(ValueError, match=r"cannot drop or update.*corrupt.*index "):