首页 > 技术文章 > 多级索引

cgmcoding 2020-11-05 10:09 原文

一、创建多级索引

1、通过pd.MultiIndex.from_tuple或from_arrays

1.1直接从元组列表创建多重索引

tuples = [('A','a'),('A','b'),('B','a'),('B','b')]
mul_index = pd.MultiIndex.from_tuples(tuples, names=('Upper', 'Lower'))
tmp=pd.DataFrame({'Score':['perfect','good','fair','bad']},index=mul_index)
'''
               Score
Upper Lower         
A     a      perfect
      b         good
B     a         fair
      b          bad
'''
tmp.index
'''
MultiIndex([('A', 'a'),
            ('A', 'b'),
            ('B', 'a'),
            ('B', 'b')],
           names=['Upper', 'Lower'])
'''
#要注意看,其实索引也是有名字的

1.2利用zip创建元组

多重索引本质上的结构是一个由元组构成的list

L1 = list('AABB')
L2 = list('abab')
tuples = list(zip(L1,L2))
mul_index = pd.MultiIndex.from_tuples(tuples, names=('Upper', 'Lower'))
pd.DataFrame({'Score':['perfect','good','fair','bad']},index=mul_index)
'''
MultiIndex([('A', 'a'),
            ('A', 'b'),
            ('B', 'a'),
            ('B', 'b')],
           names=['Upper', 'Lower'])
'''

 注意,如果用于创建多重索引的由tuple组成的list本身是未排序的, 那么创建的df也未排序。

pd.DataFrame({'Score':['perfect','good','fair','bad']},index=pd.MultiIndex.from_tuples(list(zip(L2,L1)), names=('Lower', 'Upper')))
'''
               Score
Lower Upper         
a     A      perfect
b     A         good
a     B         fair
b     B          bad
'''

 

 为了便于使用, 可以在后面使用sort_index()进行排序

pd.DataFrame({'Score':['perfect','good','fair','bad']},index=pd.MultiIndex.from_tuples(list(zip(L2,L1)), names=('Lower', 'Upper'))).sort_index()

 

1.3通过Array(或列表构成的列表)创建

内层的list会自动转成元组,仔细看一下输出的结果

arrays = [['A','a'],['A','b'],['B','a'],['B','b']]
mul_index = pd.MultiIndex.from_tuples(arrays, names=('Upper', 'Lower'))
pd.DataFrame({'Score':['perfect','good','fair','bad']},index=mul_index)
'''
               Score
Upper Lower         
A     a      perfect
      b         good
B     a         fair
      b          bad
'''

#如果创建之初未排序,创建的多重索引也是未排序的,其实只是索引值第一个索引没有排序,导致不能折叠
arrays = [['A','a'],['B','a'],['A','b'],['B','b']]
mul_index = pd.MultiIndex.from_tuples(arrays, names=('Upper', 'Lower'))
pd.DataFrame({'Score':['perfect','good','fair','bad']},index=mul_index)
'''
               Score
Upper Lower         
A     a      perfect
B     a         good
A     b         fair
B     b          bad
'''

注意:不管是上面那种创建方式都必须将索引转化为list才能用pd.MultiIndex.from_tuples 函数创建层次化索引。使用上述多重索引创建df后,要记得多加一个sort_index(), 以使得df的结果看起来更整齐。

可以通过下面查看用法,具体就不复制上来了

pd.MultiIndex.from_tuples??
# tuples: list / sequence of tuple-likes Each tuple is the index of one row/column.

 

2.通过from_product

笛卡尔乘积---可能很多时候并不需要用笛卡儿积的所有结果作为索引

L1 = ['A','B']
L2 = ['a','b']
pd.MultiIndex.from_product([L1,L2],names=('Upper', 'Lower'))
'''
MultiIndex([('A', 'a'),
            ('A', 'b'),
            ('B', 'a'),
            ('B', 'b')],
           names=['Upper', 'Lower'])
'''
#这种直接构建笛卡尔积,就不需要将每个单词打出来

 

3.指定df中的列创建(set_index方法)

传入两个以上的列名时,必须以list的形式传入(tuple不行)。注意原来的索引'ID'已经被丢弃了--这是因为set_index的 drop 参数默认值  drop=True。

#注意下面的df没有具体的数据
df_using_mul = df.set_index(['Class','Address']) 
df_using_mul.head()

#由于drop参数默认值是True,上述语法并不等价于分别将两列设置为索引。
df1= df.set_index('Class')

#第二次将某列设置为索引时,会丢弃原来的索引
df2 = df1.set_index('Address')

#第二次指定索引时,必须指定参数 append=True 才会保留原来的索引---这个参数默认是False(丢弃原始索引)。

df3= df1.set_index('Address',append=True)

df.set_index??

 

 注意的是:这个索引是针对列作为索引的,而不是自己构造的list等等

可以看我其他的文章:https://www.cnblogs.com/cgmcoding/p/13691142.html

二、多层索引切片

上面已经接介绍了怎么创建多层索引,接下来说一下索引的切片

使用第一层的索引,会把该索引下的所有行都选中,除非该索引的二级索引只有一个,否则返回行数不会等于一行。

df_using_mul.loc['C_1']

如何获取次级索引为指定值的行?? 

方法1:交换索引层级,后面可以细究交换层级的函数swaplevel

df_using_mul.swaplevel('Class','Address').loc['street_1']

方法2: 使用针对索引的 get_level_values 函数,指定索引层级为第二层

df_using_mul.loc[df_using_mul.index.get_level_values(1) == 'street_1']

方法3:使用query方法,传入 次级索引名称等于指定值--需要使用引号 

df_using_mul.query('Address == "street_1"')

 

相当于将内层索引当作列,等价于

select * from df_using_mul where Address = 'street_1'

#对原始df使用query可以获取同样的行
f.query('Address=="street_1"')

方法4:使用pd.IndexSlice对层次索引按次级索引的值进行切片

df_using_mul.loc(axis=0)[pd.IndexSlice[:, 'street_1']]

 

1.一般切片

#当索引不排序时,单个索引会报出性能警告
df_using_mul.loc['C_2','street_5']

#该函数检查索引是否排序
df_using_mul.index.is_lexsorted()

#根据索引排序后不再报出性能警告
df_using_mul.sort_index().loc['C_2','street_5']

#当不排序时,不能使用多层切片
f_using_mul.loc[('C_2','street_5'):] #报错

#故先要进行排序,注意此处由于使用了loc,因此仍然包含右端点
df_using_mul.sort_index().loc[('C_2','street_6'):('C_3','street_4')]

#使用索引标签进行切片, 是个闭区间非元组也是合法的,表示选中该层所有元素
df_using_mul.sort_index().loc[('C_2','street_7'):'C_3'].head()
df_using_mul.sort_index().loc['C_1':'C_2']#.head(10)

 

 

具体可以查看文章https://mp.weixin.qq.com/s/lq9SukMgCK7kam7HHu-4gA

 

推荐阅读