import pandas as pd
import numpy as np
# 新建df數據
df = pd.DataFrame(np.random.randint(50, 100, size=(4, 4)),
columns=pd.MultiIndex.from_product(
[['math', 'physics'], ['term1', 'term2']]),
index=pd.MultiIndex.from_tuples(
[('class1', 'LiLei'), ('class2', 'HanMeiMei'),
('class2', 'LiLei'), ('class2', 'HanMeiMei')]))
df.index.names = ['class', 'name']
# >>輸出df:

行索引取值
# 取外層索引為'class1'的數據
df.loc['class1']

# 同時根據多個索引篩選取值,法一:
df.loc[('class2', 'HanMeiMei')]

# 同時根據多個索引篩選取值,法二:
df.loc['class2'].loc['HanMeiMei']

# 取內層索引:
# 先交換內外層索引位置
df.swaplevel()
# 輸出:
math physics
term1 term2 term1 term2
name class
LiLei class1 81 81 77 91
HanMeiMei class2 82 83 84 79
LiLei class2 78 50 81 64
HanMeiMei class2 59 94 89 52
# 再通過取外層索引的方法取值
df.swaplevel().loc['HanMeiMei']

列索引取值
df數據:

# 外層列索引:
df['math']

# 根據多層索引聯合取值:
# 以下4句代碼等效:
df['math','term2']
df.loc[:, ('math','term1')]
df['math']['term2']
df[('math','term1')]

# 與行索引類似,取內層索引先交換軸
df.swaplevel(axis=1)

# 交換軸后取外層列索引即可
df.swaplevel(axis=1)['term1']
