Skip to content

ENH: Adding an empty level at the end of a multi index #62558

@HichemAK

Description

@HichemAK

Feature Type

  • Adding new functionality to pandas

  • Changing existing functionality in pandas

  • Removing existing functionality in pandas

Problem Description

Hello,

I apologize if this was discussed before, if the solution to this already exists, or if this is irrelevant.

Basically, I wish there was a simple function to add a level in a multi index (in my case, it is a multi index columns) at a given position. As of now the only solution I found was to recreate the multi index completely with an additional level (see below)

I find this useful to concatenate two dataframes (axis=1) with a different number of levels in the columns.

Feature Description

Add a new function to MultiIndex.insert_level(position : int, value : Any | Iterable[Any])

I just thought maybe supporting multiple values can be useful to specify exactly what the new level should contain. If there is only one value, fill all the level with this value.

I'm not sure about the arguments "position" and "value" although insert_level feels nice.

Alternative Solutions

new_columns = pd.MultiIndex.from_tuples(
    [col + ('',) if isinstance(col, tuple) else (col, '') 
     for col in df.columns]
)
df.columns = new_columns

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions