熊猫:如何创建一个多索引的数据透视表

时间:2016-07-05 14:05:11

标签: python pandas dataframe pivot multi-index

我有一组由两个变量定义的实验: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 个答案:

答案 0 :(得分: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
相关问题