1

I have the follow Python Pandas Table:

enter image description here

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

enter image description here

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

Like this:

-Peat-Forming      
    -PBL_AWI       Values...
    -Description   Values...
2
  • 1
    Is this just a formatting thing? If you need finer control over how the output looks you can use xlsxwriter.readthedocs.org (which pandas uses saving to xlsx) to manually specify an output layout, although it will obviously be a lot more code. Or you can do something similar for HTML. Commented Aug 14, 2014 at 23:09
  • @chrisb Maybe, I can try playing around on the Excel side to get what I want. Do you happen to know off the cuff how to get sub-totals for the Non-Peatlands and Peatlands? Was thinking of spilting the tables (b = p_table.loc['Non-Peatlands']) Add an Total row and then append both tables back together. Hopefully having an overall total as well. I realize this is outside scope of my question, just I just post new one? Commented Aug 14, 2014 at 23:29

1 Answer 1

1

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()

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.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.