Skip to content

Commit 70e628d

Browse files
committed
deep copy _indexes (#3899)
1 parent f65582a commit 70e628d

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ New Features
4242

4343
Bug fixes
4444
~~~~~~~~~
45+
- Fix a regression where deleting a coordinate from a copied :py:class:`DataArray`
46+
can affect the original :py:class:`Dataarray`. (:issue:`3899`, :pull:`3871`)
47+
By `Todd Jennings <https://github.com/toddrjen>`_
4548

4649

4750
Documentation

xarray/core/dataarray.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -930,7 +930,10 @@ def copy(self, deep: bool = True, data: Any = None) -> "DataArray":
930930
"""
931931
variable = self.variable.copy(deep=deep, data=data)
932932
coords = {k: v.copy(deep=deep) for k, v in self._coords.items()}
933-
indexes = self._indexes
933+
if self._indexes is None:
934+
indexes = self._indexes
935+
else:
936+
indexes = {k: v.copy(deep=deep) for k, v in self._indexes.items()}
934937
return self._replace(variable, coords, indexes=indexes)
935938

936939
def __copy__(self) -> "DataArray":

xarray/tests/test_dataarray.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4974,3 +4974,28 @@ def test_weakref():
49744974
a = DataArray(1)
49754975
r = ref(a)
49764976
assert r() is a
4977+
4978+
4979+
def test_delete_coords():
4980+
"""Make sure that deleting a coordinate doesn't corrupt the DataArray.
4981+
See issue #3899.
4982+
4983+
Also test that deleting succeeds and produces the expected output.
4984+
"""
4985+
a0 = DataArray(
4986+
np.array([[1, 2, 3], [4, 5, 6]]),
4987+
dims=["y", "x"],
4988+
coords={"x": ["a", "b", "c"], "y": [-1, 1]},
4989+
)
4990+
assert_identical(a0, a0)
4991+
4992+
a1 = a0.copy()
4993+
del a1.coords["y"]
4994+
4995+
# This test will detect certain sorts of corruption in the DataArray
4996+
assert_identical(a0, a0)
4997+
4998+
assert a0.dims == ("y", "x")
4999+
assert a1.dims == ("y", "x")
5000+
assert set(a0.coords.keys()) == {"x", "y"}
5001+
assert set(a1.coords.keys()) == {"x"}

0 commit comments

Comments
 (0)