Great explanation of MultiIndex in Pandas

Pandas is a widely popular component of the scientific python stack, and it is truly an indispensable part of the data scientist’s toolkit. The name pandas is actually a portmanteau created from panel and data. Of course, most of us are familiar with dataframes. But what’s a panel?

Panel data contain 3-dimensional data. A very common example is a time-series: Imagine a dataset with the stock (e.g., AAPL, MSFT, etc.) as the index defining the x axis and the price as the variable defining the y axis. A regular 2-dimensional dataframe works fine if you are only taking a cross-sectional snapshot of stock prices at one point in time. But the moment you want to look at patterns in price over the last few months, then time becomes a new index defining the z axis. A panel is a specific data structure designed to accommodate this.

Recently, the Pandas team announced the deprecation of the panel data structure (as of version 0.20.0). Rather, they are encouraging the use of dataframes with hierarchical indexing (MultiIndex). Using a MultiIndex, one may easily process 3-dimensional data in a dataframe — and indeed, any number of dimensions becomes possible.

MultiIndex is intuitive once you learn how to use it, but it can be tricky to wrap your head around it at first. Kevin Markham of the Data School released a great tutorial explaining how to use the MultiIndex in Pandas.

Read more about hierarchical indexing in the official Pandas documentation.

The QuantEcon tutorial site provides a “real-world” example that demonstrates the use of MultiIndex for analysis of 3-dimensional data.

Leave a Reply

Your email address will not be published. Required fields are marked *