Skip to content

Commit 4321ce0

Browse files
authored
avoid casting custom indexes in Dataset.drop_attrs (#10961)
* use `xindexes` when checking for indexes * check that the fix works * whats-new
1 parent ce59bda commit 4321ce0

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ Bug Fixes
4141
By `Ian Hunt-Isaak <https://github.com/ianhi>`_.
4242
- Always normalize slices when indexing ``LazilyIndexedArray`` instances (:issue:`10941`, :pull:`10948`).
4343
By `Justus Magin <https://github.com/keewis>`_.
44+
- Avoid casting custom indexes in ``Dataset.drop_attrs`` (:pull:`10961`)
45+
By `Justus Magin <https://github.com/keewis>`_.
4446

4547
Documentation
4648
~~~~~~~~~~~~~

xarray/core/dataset.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10475,7 +10475,7 @@ def drop_attrs(self, *, deep: bool = True) -> Self:
1047510475
for var in self.variables:
1047610476
# variables don't have a `._replace` method, so we copy and then remove
1047710477
# attrs. If we added a `._replace` method, we could use that instead.
10478-
if var not in self.indexes:
10478+
if var not in self.xindexes:
1047910479
self[var] = self[var].copy()
1048010480
self[var].attrs = {}
1048110481

xarray/tests/test_dataset.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4868,6 +4868,19 @@ def test_drop_attrs(self) -> None:
48684868
assert list(result.data_vars) == list(ds.data_vars)
48694869
assert list(result.coords) == list(ds.coords)
48704870

4871+
def test_drop_attrs_custom_index(self):
4872+
class CustomIndex(Index):
4873+
@classmethod
4874+
def from_variables(cls, variables, *, options=None):
4875+
return cls()
4876+
4877+
ds = xr.Dataset(coords={"y": ("x", [1, 2])}).set_xindex("y", CustomIndex)
4878+
# should not raise a TypeError
4879+
ds.drop_attrs()
4880+
4881+
# make sure the index didn't disappear
4882+
assert "y" in ds.xindexes
4883+
48714884
def test_assign_multiindex_level(self) -> None:
48724885
data = create_test_multiindex()
48734886
with pytest.raises(ValueError, match=r"cannot drop or update.*corrupt.*index "):

0 commit comments

Comments
 (0)