Adding MultiIndex Levels to a DataFrame
Based on these sources:
- https://stackoverflow.com/questions/14744068/prepend-a-level-to-a-pandas-multiindex
- http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html
If you want to add (prepend really) a level to a
pandas
DataFrame
columnMultiIndex
, you can simply usepd.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