Ben Chuanlong Du's Blog

It is never too late to learn.

Add level to a MultiIndexes in pandas

In [8]:
import numpy as np
import pandas as pd
from numpy.random import randn
In [9]:
from beakerx import beakerx, TableDisplay

beakerx.pandas_display_default()
In [11]:
df = pd.DataFrame(
    {"month": [1, 4, 7, 10], "year": [2012, 2014, 2013, 2014], "sale": [55, 40, 84, 31]}
)
df
Out[11]:
month year sale
0 1 2012 55
1 4 2014 40
2 7 2013 84
3 10 2014 31

Add a Level to Row Index

In [18]:
df2 = pd.concat([df], keys=["Foo"], names=["Firstlevel"])
df2
Out[18]:
month year sale
Firstlevel
Foo 0 1 2012 55
1 4 2014 40
2 7 2013 84
3 10 2014 31
In [19]:
df2.index
Out[19]:
MultiIndex(levels=[['Foo'], [0, 1, 2, 3]],
           labels=[[0, 0, 0, 0], [0, 1, 2, 3]],
           names=['Firstlevel', None])
In [20]:
df2.columns
Out[20]:
Index(['month', 'year', 'sale'], dtype='object')

Add a Level to Column Index

In [15]:
df3 = pd.concat([df], keys=["Foo"], names=["Firstlevel"], axis=1)
df3
Out[15]:
Firstlevel Foo
month year sale
0 1 2012 55
1 4 2014 40
2 7 2013 84
3 10 2014 31
In [16]:
df3.columns
Out[16]:
MultiIndex(levels=[['Foo'], ['month', 'year', 'sale']],
           labels=[[0, 0, 0], [0, 1, 2]],
           names=['Firstlevel', None])
In [17]:
df3.index
Out[17]:
RangeIndex(start=0, stop=4, step=1)

Comments