Saswat Ray
Saswat Ray

Reputation: 197

How to convert column header style from horizontal to vertical in pandas dataframe having multiindex?

Below is the my current multiindex column header

enter image description here

I want it to be displayed like this

enter image description here

Upvotes: 0

Views: 980

Answers (2)

user15420598
user15420598

Reputation: 227

May not answer the original 'multiindex' question but useful for formatting header row and display precision when using table_style

def mdf_format_vertical_headers(df,height_str='100px',transform_str='rotate(-90deg)',precision=3):
"""Display a dataframe with vertical column headers. Returns a styler object - Only affects display so cant use .head() etc
rotate(-90deg) - rotates the text by 90 degrees. default. TBD why negative numbers
rotate(-80deg) - rotates the text by 80 degrees

"""
styles = [dict(selector="th", props=[('width', '40px')]),
          dict(selector="th.col_heading",
               props=[("writing-mode", "horizontal"),
                      ('transform',transform_str ), 
                      ('height', height_str),
                      ('vertical-align', 'top')])]
 
return (df.fillna('').style.set_table_styles(styles).format(precision=precision))

Upvotes: 0

jcaliz
jcaliz

Reputation: 4021

You cant try modifying the HTML style of the dataframe, try adjusting the hegiht property:

styles = [dict(
     selector="th.col_heading.level1",
     props=[("transform", "rotate(270deg);"),
            ("height", "100px")]
)]
      
df.style.set_table_styles(styles)

Upvotes: 1

Related Questions