Apply multiple styles to cell in pandas

894 Views Asked by At

So, basically I want to apply styles to cell and render to html.

This is what I have done so far:

import pandas as pd
import numpy as np
data = [dict(order='J23-X23', num=5, name='foo', value='YES'),
            dict(order='Y23-X24', num=-4, name='bar', value='NO'),
            dict(order='J24-X24', num=6, name='baz', value='NO'),
            dict(order='X25-X24', num=-2, name='foobar', value='YES')]
df = pd.DataFrame(data)

def condformat(row):
    cellBGColor = 'green' if row.value == 'YES' else 'blue'
    color = 'background-color: {}'.format(cellBGColor)
    return (color, color, color, color)

s = df.style.apply(condformat, axis=1)
with open('c:/temp/test.html', 'w') as f:
   f.write(s.render())

My problem is two fold: (1) Am I using the right rendering? Or is there a better way to do this? As in what does to_html give me? (2) What if I have to add another style, say make -ve numbers in the format (35) in red color?

1

There are 1 best solutions below

0
On

So, after battling with trial-error:

s = df.style.apply(condformat, axis=1).applymap(dataframe_negative_coloring)

with a new method:

def dataframe_negative_coloring(value):
    ''' Colors Dataframe rows with alternate colors.'''
    color = 'red' if value < 0 else 'black'
    return 'color: %s' % color

Any purists out there, feel free to advice if I can make this better