Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

import numpy as np
import pandas as pd
from numpy.random import randn

from_tuples

arrays = [
    ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
    ["one", "two", "one", "two", "one", "two", "one", "two"],
]
tuples = list(zip(*arrays))
tuples
[('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('foo', 'two'), ('qux', 'one'), ('qux', 'two')]
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
index
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'])
import numpy as np

s = pd.Series(np.random.randn(8), index=index)
s
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
pd.MultiIndex.from_tuples([(jj.index.name, v) for v in jj.index.values])

Multi-Index

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

Create a MultiIndex Using set_index

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

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

df.set_index("month")
Loading...

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

df.set_index(["year", "month"])
Loading...

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

df.set_index([[4, 3, 2, 1], "year"])
Loading...