Skip to content

Commit c47cb38

Browse files
committed
Do not change coordinate inplace when throwing error (pydata#5957)
1 parent 5db4046 commit c47cb38

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

xarray/core/dataset.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ def merge_indexes(
224224
vars_to_remove: List[Hashable] = []
225225
dims_to_replace: Dict[Hashable, Hashable] = {}
226226
error_msg = "{} is not the name of an existing variable."
227+
keep_attrs = _get_keep_attrs(default=True)
227228

228229
for dim, var_names in indexes.items():
229230
if isinstance(var_names, str) or not isinstance(var_names, Sequence):
@@ -277,7 +278,8 @@ def merge_indexes(
277278
for n in names:
278279
dims_to_replace[n] = dim
279280

280-
vars_to_replace[dim] = IndexVariable(dim, idx)
281+
attrs = variables[var_names[0]].attrs if keep_attrs else None
282+
vars_to_replace[dim] = IndexVariable(dim, idx, attrs=attrs)
281283
vars_to_remove.extend(var_names)
282284

283285
new_variables = {k: v for k, v in variables.items() if k not in vars_to_remove}

xarray/tests/test_dataset.py

+9
Original file line numberDiff line numberDiff line change
@@ -2976,6 +2976,15 @@ def test_set_index(self):
29762976
ds.set_index(foo="bar")
29772977
assert str(excinfo.value) == "bar is not the name of an existing variable."
29782978

2979+
# ensure attrs are kept
2980+
da = DataArray([1, 2], dims=["x"])
2981+
da.coords["x"] = (["x"], [2, 3], {"name": "coord_1"})
2982+
da.coords["a"] = (["x"], [0, 1], {"name": "coord_2"})
2983+
ds = Dataset({"x_var": da})
2984+
assert ds.set_index(x="a").x.attrs == {"name": "coord_2"}
2985+
with set_options(keep_attrs=False):
2986+
assert ds.set_index(x="a").x.attrs == {}
2987+
29792988
def test_reset_index(self):
29802989
ds = create_test_multiindex()
29812990
mindex = ds["x"].to_index()

0 commit comments

Comments
 (0)