Member-only story
How to flatten MultiIndex Columns and Rows in Pandas
6 Tricks to effectively flatten MultiIndex columns and rows in a Pandas DataFrame

A MultiIndex (also known as a hierarchical index) DataFrame allows you to have multiple columns acting as a row identifier and multiple rows acting as a header identifier.

MultIndex is very useful for doing sophisticated data analysis, especially for working with higher dimensional data. Pandas has various methods that can output a MultIndex DataFrame, for instance, groupby()
, melt()
, pivot_table()
, stack()
etc. However, sometimes it’s just easier to work with a single-level index in a DataFrame.
In this article, you’ll learn how to flatten MultiIndex columns and rows. This article is organized as follows:
- Flatten columns: use
get_level_values()
- Flatten columns: use
to_flat_index()
- Flatten columns: join column labels
- Flatten rows: flatten all levels
- Flatten rows: flatten a specific level
- Flatten rows: join row labels