title: Conditionally Apply In-Line Style Format to HTML Table with Python
body: <p>I'm embedding a dataframe into an email's body as an html table. I want to conditionally format the cell colors and text colors based on the values in each cell.</p>
  
  <p>I first read in some data from an example csv file and format it as an html table using the <code>pandas</code> <code>to_html()</code> method:</p>
  
  <pre><code>df = pd.read_csv('example.csv')
  table = df.to_html()
  </code></pre>
  
  <p>Now I create some basic html with <code>&lt;style&gt;</code> tags for the message body and insert the <code>table</code> html code into a <code>&lt;div&gt;</code> in the body of the <code>msg</code> string as follows:</p>
  
  <pre><code>msg = """&lt;html&gt;
          &lt;style type = "text/css"&gt;
              table, th, td { border: 1px solid black; }
          &lt;/style&gt;
          &lt;head&gt;&lt;/head&gt;
          &lt;body&gt;
              &lt;p&gt;some text&lt;/p&gt;
              &lt;div&gt; %s &lt;/div&gt;
          &lt;/body
      &lt;/html&gt;""" % (table)
  </code></pre>
  
  <p>I then convert the <code>&lt;style&gt;</code> css code to in-line styling using the <code>premailer</code> python module as such:</p>
  
  <pre><code>from premailer import transform
  result = transform(msg)
  </code></pre>
  
  <p>Now <code>result</code> is a string of html with a table that has in-line styling like <code>&lt;table border="1" class="dataframe" style="border:1px solid black"&gt;</code></p>
  
  <p>I embed the resulting html in the email with:</p>
  
  <pre><code>msg_body = MIMEText(result, 'html')
  msg.attach(msg_body)
  </code></pre>
  
  <p>This all works great.</p>
  
  <p>Now I need to conditionally format the cell colors and font colors based on the values in each cell.</p>
  
  <p>How can I best do this?
  Was thinking some function such as:</p>
  
  <pre><code>def styleTable(x):
    if x &lt; 0:
      return 'background-color: red'
    else
      return ''
  </code></pre>
  
  <p>But how can I apply this to my html string? Or do I need to do something different up-stream?</p>
  
  <p>Again, this will be embedded in an email so cannot have Javascript or CSS code in it. Thanks</p>