Pandas to_html cannot apply style

Thomas Jollans tjol at tjol.eu
Mon Oct 30 04:03:05 EDT 2017


On 30/10/17 08:44, zljubisic at gmail.com wrote:
> Hi,
> 
> the following code never applies style and I cannot figure out why.
> Can someone please help?
> 
> import pandas as pd
> 
> def function2(row):
>     if row.A == True:
>         color = '#FF0000'
>     else:
>         color = '#00FF00'
> 
>     background_color = 'background-color: {}'.format(color)
> 
>     return [background_color] * len(row.values)
> 
> idx = pd.date_range('01.01.2017', periods=7, freq='D')
> A = [False, True, True, False, True, False, True]
> B = np.random.randn(7)
> C = np.random.randn(7)
> 
> data = { 'A' : [False, True, True, False, True, False, True],
>         'B' : np.random.randn(7),
>         'C' : np.random.randn(7)
>         }
> 
> df = pd.DataFrame(data, index=idx)
> 
> df.style.apply(function2, axis=1)

This is not an in-place operation: it returns a style which you can then
render.

style = df.style.apply(function2, axis=1)
html = style.render()

appears to work.

> 
> html = df.style.render()
> 
> if '#FF0000' in html or '#00FF00' in html:
>     print('style applied')
> else:
>     print('style not applied')
> 
> Regards.
> 




More information about the Python-list mailing list