Skip to content

MultiIndex.set_levels and empty levels #16147

Open
@llchan

Description

@llchan

MultiIndexes with empty levels are valid, but set_levels does not account for that case:

index = pd.MultiIndex(levels=[[], []], labels=[[], []], names=['a', 'b'])
index.set_levels([], level='a')

The set_levels code that looks like

if is_list_like(levels[0]):
    raise TypeError("Levels must be list-like")

should probably be

if len(levels) > 0 and is_list_like(levels[0]):
    raise TypeError("Levels must be list-like")

While I'm looking at this, a couple other questiosn:

  • How come we only check the first element? What if levels looks like ['a', ['b']]? I think we need to do any(is_list_like(x) for x in levels), which has the additional benefit that empty levels are handled correctly.
  • Can we make the TypeError message more precise? Maybe something like ValueError("Levels must not contain list-like items")

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions