Search code examples
pythonpandasdataframepandas-styles

How to make a specific header in italics using pandas?


I am using Pandas to make an HTML table. I want one of my column headers to be in italics. I can put the whole of a header row in italics like this:

import pandas as pd
col = pd.MultiIndex.from_arrays([["", "one", "one", "two", "two"],
                                 ["a", "b", "c", "d", "e"]])
df = pd.DataFrame(data=[["first", 20, 30, 50, 80],
                        ["second", 30, 40, 90, 20],],
                 columns=col, 
                 )
df_styled = df.style.hide(axis="index")
df_styled.set_table_styles([
    {'selector': 'th.col_heading.level1', 'props': 'font-style: italic;'},
], overwrite=False)

picture of output

How do I put just one of the column headers "b" in italics?


Solution

  • You can include the physical position (col<n>) of column "b" in the CSS selector :

    df_styled.set_table_styles(
        [
            {
                "selector": "th.col_heading.level1.col1", # << here
                "props": "font-style: italic;",
            },
        ],
        overwrite=False,
    )
    

    Output :

    enter image description here