Skip to content

Commit c2d8280

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

3 files changed

Lines changed: 16 additions & 1 deletion

File tree

doc/whats-new.rst

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

6062
Documentation
6163
~~~~~~~~~~~~~

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
@@ -4882,6 +4882,19 @@ def test_drop_attrs(self) -> None:
48824882
assert list(result.data_vars) == list(ds.data_vars)
48834883
assert list(result.coords) == list(ds.coords)
48844884

4885+
def test_drop_attrs_custom_index(self):
4886+
class CustomIndex(Index):
4887+
@classmethod
4888+
def from_variables(cls, variables, *, options=None):
4889+
return cls()
4890+
4891+
ds = xr.Dataset(coords={"y": ("x", [1, 2])}).set_xindex("y", CustomIndex)
4892+
# should not raise a TypeError
4893+
ds.drop_attrs()
4894+
4895+
# make sure the index didn't disappear
4896+
assert "y" in ds.xindexes
4897+
48854898
def test_assign_multiindex_level(self) -> None:
48864899
data = create_test_multiindex()
48874900
with pytest.raises(ValueError, match=r"cannot drop or update.*corrupt.*index "):

0 commit comments

Comments
 (0)