2017-08-29 53 views
0

假設我有一個數據幀如下分組和Multiindexing一個大熊貓據幀

In [6]: df.head() 
Out[6]: 
    regiment company  name preTestScore postTestScore 
0 Nighthawks  1st Miller    4    25 
1 Nighthawks  1st Jacobson   24    94 
2 Nighthawks  2nd  Ali   31    57 
3 Nighthawks  2nd Milner    2    62 
4 Dragoons  1st  Cooze    3    70 

我有一本字典如下:

army = {'Majors' : 'Nighthawks', 'Captains' : 'Dragoons'}

,我想它,應該有一個多隻有[「軍隊」,「公司」]形式的索引。

我將如何進行?

+0

我相信這是欺騙,所以只有評論 - 使用'df = df.set_index([「團」,「公司」])' – jezrael

+0

也檢查['set_index'](http://pandas.pydata.org/pandas-docs/stable/generated /pandas.DataFrame.set_index.html) – jezrael

+0

@jezrael耶謝謝,我編輯了我的問題,這是我想問的問題 – anonymous

回答

0

如果我理解正確:

您可以使用map發現在字典中的值(使用字典解析來交換鍵/值對,因爲它們是向後):

army = {'Majors': 'Nighthawks', 'Captains': 'Dragoons'} 

df.assign(army=df.regiment.map({k:v for v, k in army.items()})).set_index(['army', 'company'], drop=True) 
        regiment  name preTestScore postTestScore 
army  company             
Majors 1st  Nighthawks Miller    4    25 
     1st  Nighthawks Jacobson   24    94 
     2nd  Nighthawks  Ali   31    57 
     2nd  Nighthawks Milner    2    62 
Captains 1st  Dragoons  Cooze    3    70