单层索引index中,我们可以轻松通过df.loc[index]来获取某一行数据,多重索引是怎么样来实现的呢,下面进行介绍。

        1、行多层索引

1 import pandas as pd
2 
3 df = pd.DataFrame({'class':['A','A','A','B','B','B','C','C'],
4                    'id':['a','b','c','a','b','c','a','b'],
5                    'value':[1,2,3,4,5,6,7,8]})
6 df.set_index(['class', 'id'],inplace=True)
7 
        pandas中多重索引multiIndex的使用
8 df.loc['A', :]
        pandas中多重索引multiIndex的使用
1 #利用df.query()来取数
2 df.query('id == "a"')
       pandas中多重索引multiIndex的使用
1 将索引变成值
pandas中多重索引multiIndex的使用

 

 获取多重索引的值,并赋值给定列

pandas中多重索引multiIndex的使用

 

 

 

         2、列多层索引

 1 dfmi = pd.DataFrame([list('abcd'),
 2                       list('efgh'),
 3                       list('ijkl'),
 4                       list('mnop')],
 5                       columns=pd.MultiIndex.from_product([['one', 'two'],
 6                                                          ['first', 'second']]))
 7 dfmi
pandas中多重索引multiIndex的使用
 8 dfmi['one']
pandas中多重索引multiIndex的使用
 9 dfmi['one']['second']
    0    b
    1    f
    2    j
    3    n
    Name: second, dtype: object
10 dfmi.loc[:, ('one', 'second')]
    0    b
    1    f
    2    j
    3    n
    Name: (one, second), dtype: object






相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
猜你喜欢
  • 2022-12-23
  • 2022-01-02
  • 2022-12-23
  • 2022-01-09
  • 2022-12-23
  • 2021-04-12
  • 2022-12-23
相关资源
相似解决方案