0

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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

you can set table styles by defining a list of styles for all columns or one column at a time:

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")

# Set the header "b" in italics
df_styled.set_table_styles([
    {'selector': 'th.col_heading.level1', 'props': 'font-style: normal;'},
    {'selector': 'th.col_heading.level1.col1', 'props': 'font-style: italic;'},
], overwrite=False)

# Display the styled DataFrame
df_styled

Comments

1

You need to specifically target that header with a unique identifier in the CSS. Since Pandas doesn't directly support individual header styling through the style method, you'd typically use a workaround by injecting HTML directly into the column name or using external CSS and JavaScript for web display.

df.columns = pd.MultiIndex.from_arrays([
["", "one", "one", "two", "two"],
["a", "<i>b</i>", "c", "d", "e"]])    
df_styled = df.style.hide(axis="index")

Comments

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.