Change the color of text within a pandas dataframe html table python using styles and css -


i have pandas dataframe:

arrays = [['midland', 'midland', 'hereford', 'hereford', 'hobbs','hobbs', 'childress',            'childress', 'reese', 'reese', 'san angelo', 'san angelo'],           ['wrf','mos','wrf','mos','wrf','mos','wrf','mos','wrf','mos','wrf','mos']] tuples = list(zip(*arrays)) index = pd.multiindex.from_tuples(tuples) df = pd.dataframe(np.random.randn(12, 4), index=arrays,                   columns=['00 utc', '06 utc', '12 utc', '18 utc']) 

the table prints df looks this:enter image description here

i color of values in 'mos' rows color , color left 2 index/header columns top header row different background color rest of cells values in them. ideas how can this?

this takes few steps:

first import html , re

from ipython.display import html import re 

you can @ html pandas puts out via to_html method.

df_html = df.to_html() 

next going generate random identifier html table , style going create.

random_id = 'id%d' % np.random.choice(np.arange(1000000)) 

because going insert style, need careful specify style our table. let's insert df_html

df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html) 

and create style tag. you. added hover effect.

style = """ <style>     table#{random_id} tr:hover {{background-color: #f5f5f5}} </style> """.format(random_id=random_id) 

finally, display it

html(style + df_html) 

function in one.

def html_with_style(df, style=none, random_id=none):     ipython.display import html     import numpy np     import re      df_html = df.to_html()      if random_id none:         random_id = 'id%d' % np.random.choice(np.arange(1000000))      if style none:         style = """         <style>             table#{random_id} {{color: blue}}         </style>         """.format(random_id=random_id)     else:         new_style = []         s = re.sub(r'</?style>', '', style).strip()         line in s.split('\n'):                 line = line.strip()                 if not re.match(r'^table', line):                     line = re.sub(r'^', 'table ', line)                 new_style.append(line)         new_style = ['<style>'] + new_style + ['</style>']          style = re.sub(r'table(#\s+)?', 'table#%s' % random_id, '\n'.join(new_style))      df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)      return html(style + df_html) 

use this:

html_with_style(df.head()) 

enter image description here

html_with_style(df.head(), '<style>table {color: red}</style>') 

enter image description here

style = """ <style>     tr:nth-child(even) {color: green;}     tr:nth-child(odd)  {color: aqua;} </style> """ html_with_style(df.head(), style) 

enter image description here

learn css , go nuts!


Comments