Skip to content

Commit

Permalink
deep copy _indexes (#3899)
Browse files Browse the repository at this point in the history
  • Loading branch information
toddrjen committed Mar 27, 2020
1 parent 14fb9d7 commit 82f78cc
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ New Features

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


Documentation
Expand Down
5 changes: 4 additions & 1 deletion xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -930,7 +930,10 @@ def copy(self, deep: bool = True, data: Any = None) -> "DataArray":
"""
variable = self.variable.copy(deep=deep, data=data)
coords = {k: v.copy(deep=deep) for k, v in self._coords.items()}
indexes = self._indexes
if self._indexes is None:
indexes = self._indexes
else:
indexes = {k: v.copy(deep=deep) for k, v in self._indexes.items()}
return self._replace(variable, coords, indexes=indexes)

def __copy__(self) -> "DataArray":
Expand Down
25 changes: 25 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4974,3 +4974,28 @@ def test_weakref():
a = DataArray(1)
r = ref(a)
assert r() is a


def test_delete_coords():
"""Make sure that deleting a coordinate doesn't corrupt the DataArray.
See issue #3899.
Also test that deleting succeeds and produces the expected output.
"""
a0 = DataArray(
np.array([[1, 2, 3], [4, 5, 6]]),
dims=["y", "x"],
coords={"x": ["a", "b", "c"], "y": [-1, 1]},
)
assert_identical(a0, a0)

a1 = a0.copy()
del a1.coords["y"]

# This test will detect certain sorts of corruption in the DataArray
assert_identical(a0, a0)

assert a0.dims == ("y", "x")
assert a1.dims == ("y", "x")
assert set(a0.coords.keys()) == {"x", "y"}
assert set(a1.coords.keys()) == {"x"}

0 comments on commit 82f78cc

Please sign in to comment.