Ben Chuanlong Du's Blog

It is never too late to learn.

Construct MultiIndexes in pandas

In [3]:
import numpy as np
import pandas as pd
from numpy.random import randn

from_tuples

In [2]:
arrays = [
    ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
    ["one", "two", "one", "two", "one", "two", "one", "two"],
]
In [5]:
tuples = list(zip(*arrays))
tuples
Out[5]:
[('bar', 'one'),
 ('bar', 'two'),
 ('baz', 'one'),
 ('baz', 'two'),
 ('foo', 'one'),
 ('foo', 'two'),
 ('qux', 'one'),
 ('qux', 'two')]
In [6]:
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
index
Out[6]:
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
           labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],
           names=['first', 'second'])
In [8]:
import numpy as np

s = pd.Series(np.random.randn(8), index=index)
s
Out[8]:
first  second
bar    one       0.290858
       two      -1.169035
baz    one      -1.004513
       two      -1.017247
foo    one       0.034182
       two      -0.486026
qux    one      -0.749825
       two       0.643422
dtype: float64
In [ ]:
 
In [ ]:
pd.MultiIndex.from_tuples([(jj.index.name, v) for v in jj.index.values])

Multi-Index

In [ ]:
pd.MultiIndex.from_product([[jj.index.name], jj.index.values])

Create a MultiIndex Using set_index

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

DataFrame.set_index can be used to create a regular index.

In [5]:
df.set_index("month")
Out[5]:
year sale
month
1 2012 55
4 2014 40
7 2013 84
10 2014 31

DataFrame.set_index can also be used to create a MultiIndex.

In [6]:
df.set_index(["year", "month"])
Out[6]:
sale
year month
2012 1 55
2014 4 40
2013 7 84
2014 10 31

Notice that in addition to column names, you can also provide a (non-string) iterable collection.

In [7]:
df.set_index([[4, 3, 2, 1], "year"])
Out[7]:
month sale
year
4 2012 1 55
3 2014 4 40
2 2013 7 84
1 2014 10 31

Comments