Search code examples
pythonhtmlcsspandaspandas-styles

Formatting of dataframe index and columns using styler


I am quite new with html and the pandas dataframe styler, but here is my problem:

I wrote the following code

import pandas as pd

df = pd.DataFrame([1000000.0, 1000000.0], index=pd.bdate_range('2017-08-01', '2017-08-02'))

styler = df.style
styler = styler.format("{:,.0f}")
styler = styler.set_properties(**{'width': '100px', 'text-align': 'right'})

Which yield the following

enter image description here

I understand how to format the various elements of the dataframe I am working with. However, I would like to format my index and column title. In particular, i would like to format my index as a date without the time, and I would like to align my column name to the right, like I did with my values. More specifically, is there an efficient to access the index and columns in the pandas styler.


Solution

  • You could try something like this, see table styles:

    import pandas as pd
    ​
    df = pd.DataFrame([1000000.0, 1000000.0], index=pd.bdate_range('2017-08-01', '2017-08-02'))
    ​
    df.index = df.index.strftime("%Y-%m-%d")
    styler = df.style
    styler = styler.format("{:,.0f}")
    styler = styler.set_properties(**{'width': '100px', 'text-align': 'right'})
    
    styler.set_table_styles(
    # select the table header with th and set it right align
        [dict(selector="th", props=[("text-align", "right")])]   
    )
    

    enter image description here