back to notes

Adding MultiIndex Levels to a DataFrame

Based on these sources:

If you want to add (prepend really) a level to a pandas DataFrame column MultiIndex, you can simply use pd.concat to do it.

means = pd.concat([means], keys=['means'], names=['Firstlevel'], axis=1)

The intent of the keys parameter is to allow you to concatenate a bunch of data frames and actually give each of them their own level in the index. If you only have one, well, it just adds that to all it's columns.

It was super useful to me when I needed to add a level to a set of data frames that I was merging.



last updated july 2017