在Python Pandas中堆叠/取消堆叠多索引透视表
我有一个这样的Python Pandas表格:
我想把它变成这样:
我该如何将“Peat-Forming”进行堆叠或展开,以便“PBL_AWI”和“Description”可以在下面显示呢?
像这样:
-Peat-Forming
-PBL_AWI Values...
-Description Values...
1 个回答
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()
对于总计的部分,你需要计算并添加到 peat 和 non_peatlands 的数据框中。你可能需要调整一下 MultiIndex,才能让它们合并在一起。比如说,peat.index = pd.MultiIndex('设置正确的索引,可能需要用元组')
,总泥炭地的元组看起来像这样 ("Total Peatlands","")
,这样才能让单元格正确合并。
如你所见,我的答案有点儿“hacky”(但可行),只是用 pandas 实现的。我还是建议使用 xlsxwriter,就像 @user765015 说的那样。