2016-07-05 64 views
2

我有一套由兩個變量定義的實驗:scenarioheight。對於每一個實驗,我把3次測量:結果1,2和3 收集所有的結果數據框看起來是這樣的:熊貓:如何創建一個多索引樞軸

import numpy as np 
import pandas as pd 

df = pd.DataFrame() 
df['Scenario']= np.repeat(['Scenario a','Scenario b','Scenario c'],3) 
df['height'] = np.tile([0,1,2],3) 
df['Result 1'] = np.arange(1,10) 
df['Result 2'] = np.arange(20,29) 
df['Result 3'] = np.arange(30,39) 

如果我運行以下命令:

mypiv = df.pivot('Scenario','height').transpose() 
writer = pd.ExcelWriter('test_df_pivot.xlsx') 
mypiv.to_excel(writer,'test df pivot') 
writer.save() 

我獲得一個數據幀,其中列是scenarios,行有一個多指數resultheight定義:

+----------+--------+------------+------------+------------+ 
|   | height | Scenario a | Scenario b | Scenario c | 
+----------+--------+------------+------------+------------+ 
| Result 1 |  0 |   1 |   4 |   7 | 
|   |  1 |   2 |   5 |   8 | 
|   |  2 |   3 |   6 |   9 | 
| Result 2 |  0 |   20 |   23 |   26 | 
|   |  1 |   21 |   24 |   27 | 
|   |  2 |   22 |   25 |   28 | 
| Result 3 |  0 |   30 |   33 |   36 | 
|   |  1 |   31 |   34 |   37 | 
|   |  2 |   32 |   35 |   38 | 
+----------+--------+------------+------------+------------+ 

如何創建索引交換的樞紐,即首先是height,然後是result

我找不到直接創建它的方法。我設法得到我想要的交換水平和重新排序結果:

mypiv2 = mypiv.swaplevel(0,1 , axis=0).sortlevel(level=0,axis=0,sort_remaining=True) 

但我想知道是否有更直接的方法。

回答

1

可以先set_index,然後用stackunstack

print (df.set_index(['height','Scenario']).stack().unstack(level=1)) 
Scenario   Scenario a Scenario b Scenario c 
height            
0  Result 1   1   4   7 
     Result 2   20   23   26 
     Result 3   30   33   36 
1  Result 1   2   5   8 
     Result 2   21   24   27 
     Result 3   31   34   37 
2  Result 1   3   6   9 
     Result 2   22   25   28 
     Result 3   32   35   38 
+0

它是如何工作的? – jezrael