I have seen similar posts but have not found an answer that works. I am trying to style a very large Pandas dataframe.
I have a function like the following. All it does is assign a red background to negative values and a green background to positive values.
def integerFormatting(val):
"""Styling function: apply red font color to negative values."""
if int(val) > 0:
color = 'red'
else:
color = 'green'
return f'color: {color}'
I style the entire dataframe:
styled = df.style.applymap(percentFormatting)
And finally output to HTML:
result = styled.to_html()
The problem is the green styling only applies to the first 150 rows or so. This is because there are so many cells that are green there are too many selectors.
- I am aware this is an issue with the browser, not with Pandas.
- I am aware splitting the DF is a possibility, but in this case it is impractical.
- I am aware exporting to Excel works, but I need the output as HTML.
Instead of selectors, how can I apply a class or something to all the values that need to be green?
I think this part of the documentation has the answer. I just do not know how to apply that code to my situation. I have been at this for a while, and help is appreciated. Thanks!
StackOverflow post with possible answer
CodePudding user response:
All of the links you cite tell you exactly how to do it. The pandas own documentation even gives you a direct example of what to do. The example below refactors pandas own documentation.
df = pd.DataFrame([[-1, 2], [3, -2]], index=["a", "b"], columns=["c", "d"])
color_neg = lambda v: "cls-green" if v > 0 else "cls-red"
classes = df.applymap(color_neg)
styler = df.style.set_table_styles([
{'selector': '.cls-red', 'props': 'color:red;'},
{'selector': '.cls-green', 'props': 'color:green;'},
]).set_td_classes(classes)
styler.to_html()
<style type="text/css">
#T_5dcad .cls-red {
color: red;
}
#T_5dcad .cls-green {
color: green;
}
</style>
<table id="T_5dcad">
<thead>
<tr>
<th > </th>
<th id="T_5dcad_level0_col0" >c</th>
<th id="T_5dcad_level0_col1" >d</th>
</tr>
</thead>
<tbody>
<tr>
<th id="T_5dcad_level0_row0" >a</th>
<td id="T_5dcad_row0_col0" >-1</td>
<td id="T_5dcad_row0_col1" >2</td>
</tr>
<tr>
<th id="T_5dcad_level0_row1" >b</th>
<td id="T_5dcad_row1_col0" >3</td>
<td id="T_5dcad_row1_col1" >-2</td>
</tr>
</tbody>
</table>