TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial…

Follow publication

Member-only story

How to flatten MultiIndex Columns and Rows in Pandas

Robin Chan
TDS Archive
Published in
4 min readMar 12, 2022

Photo by Anastasiia Chepinska on Unsplash

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.

Pandas MultiIndex DataFrame Example (Image by author)

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:

  1. Flatten columns: use get_level_values()
  2. Flatten columns: use to_flat_index()
  3. Flatten columns: join column labels
  4. Flatten rows: flatten all levels
  5. Flatten rows: flatten a specific level
  6. Flatten rows: join row labels

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Robin Chan
Robin Chan

Responses (2)

Write a response