Skip to content

Instantly share code, notes, and snippets.

@evansde77
Created July 12, 2016 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save evansde77/7dca86894a894190f0ea24ecef75ffa6 to your computer and use it in GitHub Desktop.
Save evansde77/7dca86894a894190f0ea24ecef75ffa6 to your computer and use it in GitHub Desktop.
Formatting Pandas HTML to add styles example
import pandas
import numpy
# random data with columns A, B, C, D
df = pandas.DataFrame(numpy.random.randn(50, 4), columns=list('ABCD'))
#
# style helpers
#
def is_positive(value):
"""add styling for positive class"""
return '<div class="positive">{}</div>'.format(value)
def is_negative(value):
"""add styling for negative class"""
return '<div class="negative">{}</div>'.format(value)
def is_significant(value):
"""add styling for significant class"""
return '<div class="significant">{}</div>'.format(value)
#
# per column formatters
#
def format_column_a(value):
"""
format function that will be applied to column A
"""
if value > 0.5:
result = is_significant(value)
else:
result = str(value)
return result
def format_column_b(value):
"""
format function applied to all elements of column B
"""
if value < 0:
result = is_negative(value)
else:
result = str(value)
return result
def format_column_c(value):
"""
format funtion applied to all elements of column c
"""
result = str(value)
if value < 0:
result = is_negative(result)
else:
result = is_positive(result)
if value > 0.5:
result = is_significant(result)
return result
#
# create formatted HTML
#
html = df.to_html(
columns=['D', 'A', 'B', 'C'], # ordering columns
formatters={
"A": format_column_a,
"B": format_column_b,
"C": format_column_c
},
escape=False
)
print html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment