简体   繁体   English

Python Pandas中的堆叠/堆叠多索引数据透视表

[英]Stack/Unstack Multi-index pivot table in Python Pandas

I have the follow Python Pandas Table: 我有以下Python Pandas表:

在此处输入图片说明

I'm trying to get it to look like this: 我正在尝试使其看起来像这样:

在此处输入图片说明

How do I stack/unstack the "Peat-Forming" to have "PBL_AWI" and "Description" underneath? 如何堆叠/拆解“泥炭成型”,使其下方具有“ PBL_AWI”和“ Description”?

Like this: 像这样:

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

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. 我建议您调查xlsxwriter,但您可以尝试使用它。 (Kind of hacky though) (虽然有点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()

For the totals you. 为了总数。 calculate and append to dataframes peat and non_peatlands. 计算并附加到数据帧peat和non_peatlands。 You might have to play around with the MultiIndex to get it to merge. 您可能需要使用MultiIndex进行合并。 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. 例如peat.index = pd.MultiIndex('set the correct index probably should use from tuples') Total peat.index = pd.MultiIndex('set the correct index probably should use from tuples')组看起来像这样("Total Peatlands","")以使单元正确合并。

As you can see my answer is pretty hacky (but possible) with just the pandas implementation. 如您所见,仅使用pandas实现,我的回答就很棘手(但可能)。 I would recommend using xlsxwriter like @user765015 said 我建议使用@ user765015这样的xlsxwriter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM