Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.