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'

2 Answers 2

11

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
Sign up to request clarification or add additional context in comments.

5 Comments

Option 1 doesn't work for me, but 2 and 3 are exactly what I was looking for. Thanks a lot!
Glad to hear it. If this answer solved your problem, please click the green check mark to mark it as correct.
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.
thanks @TrentonMcKinney I have updated the answer to fix this.
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.
1

This works with me:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.