From c47cb38235ff566272608650955dc8ee917f3fd7 Mon Sep 17 00:00:00 2001 From: Giacomo Caria <44147817+gcaria@users.noreply.github.com> Date: Tue, 9 Nov 2021 21:28:13 +0100 Subject: [PATCH] Do not change coordinate inplace when throwing error (#5957) --- xarray/core/dataset.py | 4 +++- xarray/tests/test_dataset.py | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index e882495dce5..355227c6cd2 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -224,6 +224,7 @@ def merge_indexes( vars_to_remove: List[Hashable] = [] dims_to_replace: Dict[Hashable, Hashable] = {} error_msg = "{} is not the name of an existing variable." + keep_attrs = _get_keep_attrs(default=True) for dim, var_names in indexes.items(): if isinstance(var_names, str) or not isinstance(var_names, Sequence): @@ -277,7 +278,8 @@ def merge_indexes( for n in names: dims_to_replace[n] = dim - vars_to_replace[dim] = IndexVariable(dim, idx) + attrs = variables[var_names[0]].attrs if keep_attrs else None + vars_to_replace[dim] = IndexVariable(dim, idx, attrs=attrs) vars_to_remove.extend(var_names) new_variables = {k: v for k, v in variables.items() if k not in vars_to_remove} diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index cdb8382c8ee..cb55a3675de 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -2976,6 +2976,15 @@ def test_set_index(self): ds.set_index(foo="bar") assert str(excinfo.value) == "bar is not the name of an existing variable." + # ensure attrs are kept + da = DataArray([1, 2], dims=["x"]) + da.coords["x"] = (["x"], [2, 3], {"name": "coord_1"}) + da.coords["a"] = (["x"], [0, 1], {"name": "coord_2"}) + ds = Dataset({"x_var": da}) + assert ds.set_index(x="a").x.attrs == {"name": "coord_2"} + with set_options(keep_attrs=False): + assert ds.set_index(x="a").x.attrs == {} + def test_reset_index(self): ds = create_test_multiindex() mindex = ds["x"].to_index()