Search code examples
pythonpandashighlightpandas-styles

Applying styler to table replaces the values with style as plain text


I have a very huge dictionary which I am trying to highlight few rows with matching keys. To highlight specific rows in the HTML table generated from a dictionary, I am using below code. After running this code, my matching row is being displayed as Name: background-color: yellow, Age: background-color: yellow City:background-color: yellow Is there a way I could apply it as style. Any help is much appreciated

import pandas as pd
data = {
    "1": {"Name": "John", "Age": 25, "City": "New York"},
    "2": {"Name": "Jane", "Age": 30, "City": "London"},
    "3": {"Name": "Mike", "Age": 35, "City": "Paris"}
}
highlighted_rows = ["1", "3"]  # Specify the rows to highlight
df = pd.DataFrame.from_dict(data, orient="index")
df.insert(0, "Count", range(1, len(df) + 1))

# Add a CSS class to the specified rows for highlighting
df.loc[df.index.isin(highlighted_rows), :] = "background-color: yellow"

html_table = df.to_html(index=False, escape=False)
# Save the HTML table to a file
with open("table.html", "w") as file:
    file.write(html_table)

Solution

  • If you want to use your indexing strategy, you should use styler.apply:

    def color(df):
        mask = pd.DataFrame(index=df.index, columns=df.columns)
        mask.loc[df.index.isin(highlighted_rows), :] = "background-color: yellow"
        return mask
        
    html_table = (df.style.apply(color, axis=None)
                    .hide(axis='index').to_html(escape=False)
                  )
    

    Output:

    enter image description here