Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Unsparsify' a pandas multi-index when writing to Excel

I have a pandas dataframe with a multi index, by default when printing to the screen it will "sparsify" the output so that higher levels of the index are not repeated. Eg:

Sparse:

enter image description here

I can change this to "unsparse" as follows: enter image description here

However, this option is not honoured by df.to_excel(writer) which will always write the index as sparse with merged cells. Is there some way to make this write to excel in the "unsparse" way? Alternatively I can write to a csv and import it into excel, as the csv is always "unsparse", but that is a little annoying.

like image 582
phil_20686 Avatar asked Jan 22 '16 13:01

phil_20686


People also ask

How do I get rid of Multi-Level index in pandas?

By using DataFrame. droplevel() or DataFrame. columns. droplevel() you can drop a level from multi-level column index from pandas DataFrame.

How do I change multiple index in pandas?

We can easily convert the multi-level index into the column by the reset_index() method. DataFrame. reset_index() is used to reset the index to default and make the index a column of the dataframe.

Can pandas write to excel?

Write Excel with Python Pandas. You can write any data (lists, strings, numbers etc) to Excel, by first converting it into a Pandas DataFrame and then writing the DataFrame to Excel. To export a Pandas DataFrame as an Excel file (extension: . xlsx, .

How do I convert multiple index to columns in pandas?

pandas MultiIndex to ColumnsUse pandas DataFrame. reset_index() function to convert/transfer MultiIndex (multi-level index) indexes to columns. The default setting for the parameter is drop=False which will keep the index values as columns and set the new index to DataFrame starting from zero.


1 Answers

Try to apply reset_index() before writing to excel.

An example :

first  second
bar    one      -0.008620
       two       1.688653
baz    one      -0.145099
       two       0.870981
foo    one       2.544494
       two       0.935468
qux    one      -1.868521
       two      -0.118242

print(s.reset_index())

  first second         0
0   bar    one -0.008620
1   bar    two  1.688653
2   baz    one -0.145099
3   baz    two  0.870981
4   foo    one  2.544494
5   foo    two  0.935468
6   qux    one -1.868521
7   qux    two -0.118242
like image 170
DavidK Avatar answered Sep 19 '22 18:09

DavidK