Python Pandas中的堆叠/拆栈多索引数据透视表 [英] Stack/Unstack Multi-index pivot table in Python Pandas

查看:87
本文介绍了Python Pandas中的堆叠/拆栈多索引数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Python熊猫表:

I have the follow Python Pandas Table:

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

I'm trying to get it to look like this:

如何堆叠/拆解泥炭成型",使其下方具有"PBL_AWI"和"Description"?

How do I stack/unstack the "Peat-Forming" to have "PBL_AWI" and "Description" underneath?

赞:

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

推荐答案

取消堆积将在列级别中创建另一个级别,从而使其更宽.我建议您调查xlsxwriter,但您可以尝试使用它. (虽然有点hacky)

Unstacking would create another level in the columns level it would make it wide. Looking into xlsxwriter is something I recommend but you could probably try using this. (Kind of hacky though)

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('set the correct index probably should use from tuples')元组看起来像这样的("Total Peatlands",""),以使单元正确合并.

For the totals you. calculate and append to dataframes peat and non_peatlands. You might have to play around with the MultiIndex to get it to merge. eg peat.index = pd.MultiIndex('set the correct index probably should use from tuples') tuple of the Total peatlands looks like this ("Total Peatlands","") to get the cells to merge properly.

如您所见,仅使用pandas实现,我的回答就很棘手(但可能).我建议像@ user765015所说的那样使用xlsxwriter

As you can see my answer is pretty hacky (but possible) with just the pandas implementation. I would recommend using xlsxwriter like @user765015 said

这篇关于Python Pandas中的堆叠/拆栈多索引数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆