Formatting numbers after coloring dataframe using Styler (pandas)

Question:

I created a DataFrame in pandas for which I want to colour the cells using a colour index (low values red, high values green). I succeeded in doing so, however the colouring 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'

Is there anyone who can tell me what’s going wrong?

Asked By: gardangerous

||

Answers:

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 .set_precision() method of styler.
style = df.style.background_gradient(cmap='RdYlGn').set_precision(2)
style
Answered By: jkr

This works with me:

stylish_df = df.style.background_gradient(cmap='RdYlGn').format(precision=2)
Answered By: Hamzah