0

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.

Screenshot of test.html: enter image description here

BruceWayne
  • 22,923
  • 15
  • 65
  • 110

1 Answers1

0

You have the general idea, good job!

The part you need to add is actually rendering the formatting.

Before saving the html, do so like this:

...
stylized_df = df.style.applymap(style_dataframe)
with open("test.html","w") as html:
    html.write(stylized_df.render())

Note: you can't do if "bbc" in val as you get the error

TypeError: ("argument of type 'NoneType' is not iterable", 'occurred at index author')

To fix that, adjust the If statement flow:

def style_dataframe(val):
    color = "white"
    if val is not None:
        if "bbc" in val:
            color = "red"
        if val == "The Wall Street Journal":
            color = "green"
    return 'background-color: %s' % color
BruceWayne
  • 22,923
  • 15
  • 65
  • 110
  • @AsheKetchum instead of the `if not None`? – BruceWayne Jul 24 '18 at 22:09
  • @Batman Yeah, i think there's the idea about "Ask forgiveness not permission". I thought it was in the zen of python but maybe I saw it somewhere else. Maybe something like https://stackoverflow.com/a/12265860/7571052 ? I guess it doesn't make a huge difference in this case :) – AsheKetchum Jul 25 '18 at 14:38