Created
July 12, 2016 19:17
-
-
Save evansde77/7dca86894a894190f0ea24ecef75ffa6 to your computer and use it in GitHub Desktop.
Formatting Pandas HTML to add styles example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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