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]:
In [6]:
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
index
Out[6]:
In [8]:
import numpy as np
s = pd.Series(np.random.randn(8), index=index)
s
Out[8]:
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]:
DataFrame.set_index
can be used to create a regular index.
In [5]:
df.set_index("month")
Out[5]:
DataFrame.set_index
can also be used to create a MultiIndex.
In [6]:
df.set_index(["year", "month"])
Out[6]:
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]: