I've seen online how to format a Pandas DataFrame with .style
.
However, I have a table with a bunch of text, and would like to be able to format the cells, depending on the words inside. Borrowing from this logic in the above linked reference:
def color_negative_red(val):
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
For example, color the cell red if the word "BBC" is in a cell. Color it green if "XYZ" is in the cell. Color it black if "ZYX" is in the cell, etc.
def style_dataframe(val):
color = "red" if "BBC" in val else "white" # fuzzy match 'BBC'
color = "green" if val == "XYZ" else color # find exact match
color = "black" if val == "ZYX" else color # find exact match
return 'background-color: %s' % color
...
df.style.applymap(style_dataframe)
df.to_html("test.html")
However, this doesn't color anything.