Pandas MultiIndex cheatsheet
This is a quick cheatsheet on creating and indexing with Pandas MultiIndexes.
Guide
I’m representing values in the DataFrame using symbols. For a DataFrame like the one to the left, the representation I’ll use is the one on the right.
For example, A
in the sample DataFrame
is represented by the blue rectangle that look like in the images. As additional examples, B
in the sample DataFrame
is represented by , the row one
is and two
is .
Creating MultiIndexes
Four ways to create MultiIndex
es are pd.MultiIndex.from_tuples
, pd.MultiIndex.from_product
, pd.MultiIndex.from_arrays
, and pd.MultiIndex.from_frame
.
pd.MultiIndex.from_tuples |
|
pd.MultiIndex.from_arrays |
|
pd.MultiIndex.from_product |
|
pd.MultiIndex.from_frameThe column names become the names of the levels. |
Creating a sample DataFrame with MultiIndex
You can create a DataFrame
with MultiIndex
es as both the index and the columns.
MultiIndex from a group by
You can create up with a DataFrame
with a MultiIndex
by using a pivot
or groupby
using multiple columns.
Accessing columns
This section describes how to select different columns and rows using the MultiIndex
es.
This section uses the DataFrame
below, which has a MultiIndex as the columns and rows.