Skip to content
Advertisement

Styling Large Pandas Dataframe

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.

  1. I am aware this is an issue with the browser, not with Pandas.
  2. I am aware splitting the DF is a possibility, but in this case it is impractical.
  3. 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

Advertisement

Answer

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 class="blank level0" >&nbsp;</th>
      <th id="T_5dcad_level0_col0" class="col_heading level0 col0" >c</th>
      <th id="T_5dcad_level0_col1" class="col_heading level0 col1" >d</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th id="T_5dcad_level0_row0" class="row_heading level0 row0" >a</th>
      <td id="T_5dcad_row0_col0" class="data row0 col0 cls-red" >-1</td>
      <td id="T_5dcad_row0_col1" class="data row0 col1 cls-green" >2</td>
    </tr>
    <tr>
      <th id="T_5dcad_level0_row1" class="row_heading level0 row1" >b</th>
      <td id="T_5dcad_row1_col0" class="data row1 col0 cls-green" >3</td>
      <td id="T_5dcad_row1_col1" class="data row1 col1 cls-red" >-2</td>
    </tr>
  </tbody>
</table>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement