4

I created a DataFrame in pandas for which I want to color the cells using a color index (low values red, high values green). I succeeded in doing so, however the coloring prevents me to format the cells.

import pandas as pd

df = pd.DataFrame({'a': [0.5,1.5, 5],
                   'b': [2, 3.5, 7] })

df = df.style.background_gradient(cmap='RdYlGn')
df

which returns

enter image description here

However, when I try to use df.round(2) for example to format the numbers, the following error pops up:

AttributeError: 'Styler' object has no attribute 'round'

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
gardangerous
  • 67
  • 1
  • 5

2 Answers2

10

Take a look at the pandas styling guide. The df.style property returns a Styler instance, not a dataframe. From the examples in the pandas styling guide, it seems like dataframe operations (like rounding) are done first, and styling is done last. There is a section on precision in the pandas styling guide. That section proposes three different options for displaying precision of values.

import pandas as pd

df = pd.DataFrame({'a': [0.5,1.5, 5],
                   'b': [2, 3.5, 7] })

# Option 1. Round before using style.
style = df.round(2).style.background_gradient(cmap='RdYlGn')
style

# Option 2. Use option_context to set precision.
with pd.option_context('display.precision', 2):
    style = df.style.background_gradient(cmap='RdYlGn')
style

# Option 3. Use .format() method of styler.
style = df.style.format(precision=2).background_gradient(cmap='RdYlGn')
style
jkr
  • 17,119
  • 2
  • 42
  • 68
  • Option 1 doesn't work for me, but 2 and 3 are exactly what I was looking for. Thanks a lot! – gardangerous Feb 18 '21 at 14:45
  • Glad to hear it. If this answer solved your problem, please click the green check mark to mark it as correct. – jkr Feb 18 '21 at 19:21
  • 1
    Method '.set_precision' is deprecated in the current Pandas release (v1.3.1). The new method passes float precision through '.format(precision = 2)'. However, I had a problem with this and had to revert to previous Pandas version. I tried various methods as stated in the docs, but I couldn't get it to work. Perhaps an inconsistency with the older Python version I use 3.7.7. – Alex M Aug 06 '21 at 11:36
  • Option 1 does not work, Option 3 works. Thanks – Anakin Skywalker Jun 22 '22 at 11:16
  • 1
    thanks @TrentonMcKinney I have updated the answer to fix this. – jkr Jun 05 '23 at 15:31
  • You might want to just delete 3. As the other answer already covers `.format`. In any case, also update the docstring for #3 if you leave it. – Trenton McKinney Jun 05 '23 at 15:43
1

This works with me:

stylish_df = df.style.background_gradient(cmap='RdYlGn').format(precision=2)
Hamzah
  • 8,175
  • 3
  • 19
  • 43