1、生成两层行索引、列索引的样本数据
1)生成 DataFrame
import pandas as pd
import numpy as np
pd.set_option('display.max_columns', 1000)
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 1000)
df = pd.DataFrame(np.random.randint(80,150,size=(9, 9)),
columns=pd.MultiIndex.from_product([['last year', 'this year', 'next year'],['price', 'height', 'weight']]),
index=pd.MultiIndex.from_product([['xiaoming', 'lili', 'xiaohong'],['chicken', 'dog', 'cat']]))
df
Out[67]:
last year this year next year
price height weight price height weight price height weight
xiaoming chicken 148 137 121 119 95 98 90 118 110
dog 88 143 117 100 86 95 82 122 142
cat 120 93 145 137 148 136 110 99 88
lili chicken 146 86 90 91 116 134 124 116 94
dog 103 144 141 131 104 108 90 87 121
cat 120 119 88 102 129 113 131 118 98
xiaohong chicken 132 146 103 128 98 143 126 81 136
dog 129 92 99 103 84 116 99 100 85
cat 131 125 129 146 104 119 135 115 117
2)生成 Series
ser = pd.Series(np.random.randint(0,150,size=6),
index=pd.MultiIndex.from_product([['xiaoming', 'lili'],['chicken', 'dog', 'cat']]))
ser
Out[23]:
xiaoming chicken 135
dog 94
cat 74
lili chicken 24
dog 142
cat 4
dtype: int32
2、索引使用总体原则
1)在进行多重索引操作之前要对索引进行排序
df2 = df.sort_index()
df2
Out[16]:
last year this year next year
price height weight price height weight price height weight
lili cat 120 119 88 102 129 113 131 118 98
chicken 146 86 90 91 116 134 124 116 94
dog 103 144 141 131 104 108 90 87 121
xiaohong cat 131 125 129 146 104 119 135 115 117
chicken 132 146 103 128 98 143 126 81 136
dog 129 92 99 103 84 116 99 100 85
xiaoming cat 120 93 145 137 148 136 110 99 88
chicken 148 137 121 119 95 98 90 118 110
dog 88 143 117 100 86 95 82 122 142
2)索引的顺序一般是先外层,再内层
3、 索引与切片 —— Series
1)显式
从最外层开始索引, 不能直接索引最内侧层索引。
ser['lili', 'dog']
Out[27]: 142
或者
ser.loc['lili', :]
Out[28]:
chicken 24
dog 142
cat 4
dtype: int32

本文介绍了如何在Python pandas库中使用多层索引,包括DataFrame和Series的索引操作,如排序、显式和隐式切片,以及pd.IndexSlice、pd.xs()和索引转换技巧。涵盖了索引转换、命名、取值、列转行和行转列等实用技巧。
最低0.47元/天 解锁文章
853

被折叠的 条评论
为什么被折叠?



