gardangerous
gardangerous

Reputation: 67

Formatting numbers after coloring a dataframe using Styler

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'

Upvotes: 4

Views: 5997

Answers (2)

jkr
jkr

Reputation: 19280

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

Upvotes: 11

Hamzah Al-Qadasi
Hamzah Al-Qadasi

Reputation: 9786

This works with me:

stylish_df = df.style.background_gradient(cmap='RdYlGn').format(precision=2)

Upvotes: 1

Related Questions