0

I'm trying to use pandas Dataframe Styler possibilies (looks very cool). My need is to output the dataframe in both Excel, pdf and HTML format.

Here is the sample code :

import pandas as pd
from IPython.core.display import display, HTML
multi_index = pd.MultiIndex.from_tuples([("r0", "rA"),("r1", "rB")], names=['Courses','Fee'])
cols = pd.MultiIndex.from_tuples([("Gasoline", "Toyoto"), ("Gasoline", "Ford"), ("Electric", "Tesla"),("Electric", "Nio")])
data=[[100,300, 900,400 ], [200,500, 300,600]]
df = pd.DataFrame(data, columns=cols,index=multi_index)
print(df)
            Gasoline      Electric     
              Toyoto Ford    Tesla  Nio
Courses Fee                            
r0      rA       100  300      900  400
r1      rB       200  500      300  600

df_styled = df.style
df_styled = df_styled.relabel_index(("Gasoil", "Gasoil", "Elec.", "Elec."), axis=1, level=0)
print(display(HTML((df_styled.to_html()))))

        Gasoil  Elec.
        Toyoto  Ford    Tesla   Nio
Courses Fee              
r0  rA  100 300 900 400
r1  rB  200 500 300 600

df_styled.to_excel("test.xlsx", engine='openpyxl') 

When output is to_html or to_pdf, the result of the Styler.relabel_index is working but with the to_excel output, column names are not altered.

I'm looking for a way to separate data from output and i'm using relabel_index to localize dataframe.

Any hints ?

2
  • 1
    This is not yet implemented, see github.com/pandas-dev/pandas/issues/42276. However, although the TODO in section "Hiding and Concatening" of the issue claims that missing features are documented, I couldn't find this documentation. Commented Aug 28, 2024 at 6:37
  • Do someone know is there is a way to rename column names of a dataframe Styler object : i'm looking for a way to localize a dataframe before writing it to html or excel but after i added styling (in order to simplify style application) Commented Aug 29, 2024 at 18:53

0

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.