I need to color specific columns in the table and convert it to html. I know it's possible to apply pandas styling to required subsets of data; for example, the next code snippet seems to work just fine. But the problem is that I need to set the same styling using bgcolor
html attribute, not CSS
. And I have found only Styler.set_table_attributes, which doesn't really help in my case. My current approach: I'm converting the html obtained from pandas to BeautifulSoup and adding attributes there, but it's not really convenient.
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D'])
st = df.style
def highlight(c):
color = 'green' if (c > 0) else 'red'
return f'background-color:{color}'
st.applymap(highlight, subset=['C', 'D'])
with open('out.html','w') as f:
f.write(str(st.to_html()))
# how i'm doing this now:
from bs4 import BeautifulSoup
res = BeautifulSoup(df.to_html(index=False), features='html.parser')
for header in ['C', 'D']:
index = df.columns.get_loc(header)
for tr in res.table.tbody.select('tr'):
td = tr.select('td')[index]
c = float(td.text)
td.attrs['bgcolor'] = 'green' if (c > 0) else 'red'
with open('out2.html','w') as f:
f.write(str(res))
You can set the
bgcolor
attribute using pandas styling by defining a custom function that returns thebgcolor
attribute in an HTML style tag. You can then use this function with theStyler.applymap()
method to apply the styling to the required subset of data.Example:
The
render()
method of the Styler object will return the styled DataFrame as an HTML string with the bgcolor attribute set using the style tag.