1

I have a data frame with three colums $A$, $B$ and $C.$ Everything is numeric, columns $A$ and $B$ increase from worse to better while columns $C$ increases from better to worse. I want to colour the cells using a gradient column-wise such that it goes from white to red in the columns $A$ and $B$ but it is reversed in the columns $C.$

In the example below, columns Aand B produce exactly what I want. Is there a way below to tell df to use the background_gradient method reversed for the columns C?

df = pd.DataFrame({"A":[1,2,3], "B":[4,6,10], "C":[1,3,7]})
df.style.background_gradient("Reds")

1 Answer 1

2

You can just specify the cmap and chain the background_gradient:

df.style.background_gradient("Reds").background_gradient("Reds_r", subset='C')

Output:

enter image description here

In generals, if you have a mapping of column-cmap, you can do a loop:

# column-cmap mapping
cmaps = {'A': 'Reds', 'B':'Greens'}

# default gradient
style = df.style.background_gradient()

# loop
for col, cmap in cmaps.items():
    style = style.background_gradient(cmap, subset=col)
    
# view the result
style

And you get:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I wanted.

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.