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

Using pandas new styling functionality (since 0.17.1):

import numpy as np
import pandas as pd

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'])


def highlight_MOS(s):
    is_mos = s.index.get_level_values(1) == 'MOS'
    return ['color: darkorange' if v else 'color: darkblue' for v in is_mos]

s = df.style.apply(highlight_MOS)
s

enter image description here

Leave a Comment