diff --git a/doc/whats-new.rst b/doc/whats-new.rst index d77422df5b4..e47a5db9d69 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -46,6 +46,8 @@ Bug fixes By `Jimmy Westling `_. - Fix incompatibility with numpy 1.20 (:issue:`6818`, :pull:`6821`) By `Michael Niklas `_. +- Fix side effects on index coordinate metadata after aligning objects. (:issue:`6852`, :pull:`6857`) + By `BenoƮt Bovy `_. - Make FacetGrid.set_titles send kwargs correctly using `handle.udpate(kwargs)`. (:issue:`6839`, :pull:`6843`) By `Oliver Lopez `_. diff --git a/xarray/core/alignment.py b/xarray/core/alignment.py index 303eb6c0ef0..cee83bd1daf 100644 --- a/xarray/core/alignment.py +++ b/xarray/core/alignment.py @@ -467,7 +467,7 @@ def override_indexes(self) -> None: if obj_idx is not None: for name, var in self.aligned_index_vars[key].items(): new_indexes[name] = aligned_idx - new_variables[name] = var + new_variables[name] = var.copy() objects[i + 1] = obj._overwrite_indexes(new_indexes, new_variables) @@ -507,7 +507,7 @@ def _get_indexes_and_vars( if obj_idx is not None: for name, var in index_vars.items(): new_indexes[name] = aligned_idx - new_variables[name] = var + new_variables[name] = var.copy() return new_indexes, new_variables diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 9ea47163d05..e0bc73ec044 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -2333,6 +2333,20 @@ def test_align_str_dtype(self) -> None: assert_identical(expected_b, actual_b) assert expected_b.x.dtype == actual_b.x.dtype + @pytest.mark.parametrize("join", ["left", "override"]) + def test_align_index_var_attrs(self, join) -> None: + # regression test https://github.com/pydata/xarray/issues/6852 + # aligning two objects should have no side effect on their index variable + # metadata. + + ds = Dataset(coords={"x": ("x", [1, 2, 3], {"units": "m"})}) + ds_noattr = Dataset(coords={"x": ("x", [1, 2, 3])}) + + xr.align(ds_noattr, ds, join=join) + + assert ds.x.attrs == {"units": "m"} + assert ds_noattr.x.attrs == {} + def test_broadcast(self) -> None: ds = Dataset( {"foo": 0, "bar": ("x", [1]), "baz": ("y", [2, 3])}, {"c": ("x", [4])}