Skip to content

Conversation

@Reshief
Copy link

@Reshief Reshief commented Jan 23, 2026

Indexes of non-dimension variable names being lost upon ds.swap_dims() call

This is a small patch to fix the issue underlying #11099 .
Due to Indexes only being copies in Dataset.swap_dims() for variables whose names are dimensions before the call, indexes for multi-index variables and probably also for other indexed variables are lost in the resulting dataset.
This can lead to issues further down the line like .attrs being lost (as I personally encountered).

The patch copies over index variables and indexes of variables that do not lose dimension-status, making the function .swap_dims() behave consistently with .rename_dims() if the target name is not used.

I added a short test to make sure that the patch fixes the reported problem in #11099 and ran the entire test suite to make sure that no unintended changes to overall behavior that has previously been tested would be observed.

@dcherian dcherian requested a review from benbovy January 23, 2026 16:47
@dcherian
Copy link
Contributor

Thanks, seems OK to me.

If you want fix some related bugs there are a few documented here:

# TODO: swap_dims is basically all broken if a multiindex is present
# TODO: Avoid swapping from Index to a MultiIndex level
# TODO: Avoid swapping from MultiIndex to a level of the same MultiIndex
# TODO: Avoid swapping when a MultiIndex is present
@precondition(lambda self: not bool(self.multi_indexed_dims))
@precondition(lambda self: bool(self.swappable_dims))

Removing @precondition(lambda self: not bool(self.multi_indexed_dims)) should reproduce them for you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.swap_dims() loses indexes of non-dimension variables

2 participants