fix: preserve falsy but valid multi-index level names#11463
Open
Kropiunig wants to merge 1 commit into
Open
Conversation
PandasMultiIndex.__init__ used idx.name or f"{dim}_level_{i}" to fill
in default names for unnamed levels. pandas represents an unnamed level as
None, but or also discards legitimate falsy names such as the empty
string "" (or 0/False), replacing them with the synthetic
default name. That desyncs index.names from level_coords_dtype and
raises KeyError in create_variables when the multi-index is built via
public APIs such as Dataset.stack or Dataset.set_index.
Use an explicit is not None check so only truly unnamed (None) levels
receive the default name.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What happened
Building a
pandas.MultiIndex-backed index whose level name is falsy but valid — most naturally an empty string""— raisesKeyErrorthrough public APIs:An empty string is a perfectly valid coordinate name (
ds.sel({"": 20})works,"" in ds.coordsisTrue), so this is a crash on legitimate input rather than rejection of a disallowed one.Cause
PandasMultiIndex.__init__fills in default names for unnamed levels:pandas represents an unnamed level as
None, butoralso discards legitimate falsy names ("",0,False), swapping them for the synthetic{dim}_level_{i}. Meanwhilelevel_coords_dtypeis still keyed by the original name, so the two fall out of sync andcreate_variablesraisesKeyErroron the lookupself.level_coords_dtype[name].Fix
Use an explicit
is not Nonecheck so only truly unnamed (None) levels get the default name:Tests
Added a regression assertion to
TestPandasMultiIndex::test_constructorcovering a""level name (fails before, passes after). The existing default-name case (Nonelevels →x_level_0,x_level_1) is unchanged and still asserted.