Closed
Description
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?