'pandas styling add attribute for cell/column
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()))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
