Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
df = pd.DataFrame({'month': [2, 5, 8, 10],
                   'year': [2017, 2019, 2018, 2019],
                   'sale': [60, 45, 90, 36]})
df
Out[2]:
month year sale
0 2 2017 60
1 5 2019 45
2 8 2018 90
3 10 2019 36

Pandas: Dataframe - set_index

Set the index to become the ‘month’ column:

In [3]:
df.set_index('month')
Out[3]:
year sale
month
2 2017 60
5 2019 45
8 2018 90
10 2019 36

Pandas: Dataframe - Set the index to become the ‘month’ column.

Create a MultiIndex using columns ‘year’ and ‘month’:

In [4]:
df.set_index(['year', 'month'])
Out[4]:
sale
year month
2017 2 60
2019 5 45
2018 8 90
2019 10 36

Pandas: Dataframe - Create a MultiIndex using columns ‘year’ and ‘month’.

Create a MultiIndex using an Index and a column:

In [5]:
df.set_index([pd.Index([2, 3, 4, 5]), 'year'])
Out[5]:
month sale
year
2 2017 2 60
3 2019 5 45
4 2018 8 90
5 2019 10 36

Pandas: Dataframe - Create a MultiIndex using an Index and a column.

Create a MultiIndex using two Series:

In [6]:
s = pd.Series([2, 3, 4, 5])
df.set_index([s, s**2])
Out[6]:
month year sale
2 4 2 2017 60
3 9 5 2019 45
4 16 8 2018 90
5 25 10 2019 36

Pandas: Dataframe - Create a MultiIndex using two Series.