Skip to content

Respect keep_attrs when using Dataset.set_index (#4955) #5972

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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}
Expand Down
9 changes: 9 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down