Combitation of pandas set_table_styles not working

Viewed 385

In the following code (using pandas==1.3.5), the first two column are shown in red and blue:

import numpy as np
import pandas as pd

data = np.random.random(size=(10, 5))

df = pd.DataFrame(
    data=data,
    columns=list("ABCDE"),
    index=["A1", "B2", "C3", "D4", "E5", "F6", "G7", "H8", "I9", "J10"],
)

df.style.set_table_styles(
    # [
    #     {
    #         "selector": "caption",
    #         "props": [("text-align", "center"), ("font-size", "16pt")],
    #     }
    # ],
    {
        "A": [{"selector": "", "props": [("color", "red")]}],
        "B": [{"selector": "", "props": "color: blue;"}],
    },
).set_caption("test")

Once the commented out lines are added (that do work, the font size of the caption is set to 16pt), the colors are gone. How could i prevent that?

Thanks in advance!

1 Answers

Doing it this way in a Jupyter notebook, all the formatting are preserved:

styles = [
    {"selector": "caption", "props": [("text-align", "center"), ("font-size", "16pt")]}
]

(
    df.style.set_caption("test")
    .set_table_styles(styles)
    .applymap(lambda x: "color: red", subset="A")
    .applymap(lambda x: "color: blue", subset="B")
)
Related