I have a dataframe, and I would like to highlight the cells red, where the word "BBC" appears.
Looking at this SO thread and this one I tried the below:
df.style.apply(lambda x: ["background-color: red" if x == "BBC News" else "background-color: green"])
or
df.style.apply(lambda x: ["background-color: red" if v == "BBC News" else "background-color: green" for v in x], axis=None)
But this doesn't color anything. FWIW, I don't know what the x
or v
are in the examples I used. I assume x
is a cell, and v
would be a part of the cell?
How can I conditinally format cells? I'd also be adding others, i.e. if "CNN" appears in a cell, color yellow, etc.
Edit: I tried simply df.style.apply(lambda x: ["background-color: green"])
and nothing happened (same if I used #ff0000
or rgb(0,0,255)
).
To be explicit, I'm doing:
df.style.apply(lambda x: ["background-color: #ff0000" if v['newsSource'] == "BBC News" else "background-color: #ffff00"], axis=None)
df.to_html("styletest.html")
So I want the coloring visible in the HTML DOCUMENT not the dataframe itself necessarily.