Multi-level index
Multi-level index (also known as hierarchical index) is an important function of pandas, you can have more than two, and two indexes on Series, DataFrame object.
In essence, a single stage Index object corresponding to the index, the index corresponding to the multi-stage MultiIndex object.
A multi-level index Series object
- Create a multi-level index Series object
import pandas as pd import numpy as np se1=pd.Series(np.random.randn(4),index=[list("aabb"),[1,2,1,2]]) se1 Out[6]: a 1 0.357171 2 0.084055 b 1 -0.678752 2 0.132007 dtype: float64
- Select a subset
se1 [ 'a'] Out[7]: 1 0.357171 2 0.084055 dtype: float64 se1 [ 'a': 'b'] Out[8]: a 1 0.357171 2 0.084055 b 1 -0.678752 2 0.132007 dtype: float64
-
Select the inner layer
se1 [:, 1] Out[9]: a 0.357171 b -0.678752 dtype: float64 se1 [:, 2] Out[10]: a 0.084055 b 0.132007 dtype: float64
Second, and more object-level index DataFrame
- create
df1=pd.DataFrame(np.arange(12).reshape(4,3),index=[list("AABB"),[1,2,1,2]],columns=[list("XXY"),[10,11,10]]) df1 Out[11]: XY 10 11 10 A 1 0 1 2 2 3 4 5 B 1 6 7 8 2 9 10 11
- Fu name
df1.columns.names=['XY','sum'] df1.index.names=['AB','num'] df1 Out[12]: XY X Y sum 10 11 10 Surely AB A 1 0 1 2 2 3 4 5 B 1 6 7 8 2 9 10 11
- Re-create the object as an index MultiIndex
df1.index=pd.MultiIndex.from_arrays([list("AABB"),[3,4,3,4]],names=["AB","num"]) df1 Out[13]: XY X Y sum 10 11 10 Surely AB A 3 0 1 2 4 3 4 5 B 3 6 7 8 4 9 10 11
- Can be interchanged index levels
Dfalkswplevel ( 'now', 'num') Out[14]: XY X Y sum 10 11 10 Surely AB 3 A 0 1 2 4 A 3 4 5 3 B 6 7 8 4 B 9 10 11