Skip to content

Add method to flatten all multi-index levels #19950

Closed
@cbrnr

Description

@cbrnr

Sometimes it is useful to flatten all levels of a multi-index. For example, when pivoting data into a wide format, the new columns are generally multi-indexed. However, when exporting to CSV, sometimes it might be desirable to have only one header row.

AFAIK, there is no dedicated method to flatten an existing multi-index. Assuming I want to combine the multi-index levels with an underscore, I would do this to get one header row:

df.columns = ["_".join(v) for v in df.columns.values]

This is not really obvious, and maybe a dedicated MultiIndex method should be added, e.g. df.columns.flatten(sep="_", inplace=False). What do you think?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions