Stack / Unstack Python Pandas中的多索引数据透视表

时间:2014-08-14 22:46:23

标签: python pandas pivot-table

我有以下Python Pandas表:

enter image description here

我试图让它看起来像这样:

enter image description here

如何堆叠/拆除" Peat-Forming"拥有" PBL_AWI"和"描述"下方?

像这样:

-Peat-Forming      
    -PBL_AWI       Values...
    -Description   Values...

1 个答案:

答案 0 :(得分:1)

取消堆叠会在列级别创建另一个级别,使其变宽。查看xlsxwriter是我推荐的,但你可能会尝试使用它。 (虽然有点hacky)

writer = ExcelWriter('output.xlsx')
non_peatlands = df.loc['Non-Peatlands']
peat = df.loc['Peatlands']

peat.reset_index().to_excel(writer,'1',startrow=no_peatlands.shape[0])#not sure if you need to add +1 or -1 to start or not so header is overwritten play around with it
no_peatlands.reset_index().to_excel(writer,'1') #this comes second to overwrite the columns of peat frame
writer.save()

总计你。计算并附加到数据帧泥炭和非豌豆。您可能需要使用MultiIndex才能使其合并。例如,总计泥炭地的peat.index = pd.MultiIndex('set the correct index probably should use from tuples')元组看起来像("Total Peatlands",""),以使细胞合适地合并。

正如你所看到的那样,只有pandas实现,我的答案非常hacky(但可能)。我建议使用像@ user765015这样的xlsxwriter