7

I like using the background_gradient as it helps me look at my dataframes in an excel way.
But I'm wondering if I there is a way I could map the colors to the figures in another dataframe.
For example, something I am keen to do is to color the dataframe using a dataframe of zscores so i can see quickly the value of outliers.

A = pd.DataFrame(np.random.randn(6, 3), columns=['a', 'b', 'c']) 
B = pd.DataFrame(np.random.randn(6, 3), columns=['a', 'b', 'c'])
A.style.background_gradient(???)

I'm wondering how to use background_gradient so that it uses the values in the dataframe B to style A.

3
  • How to mean style A from values dataframe B. Like colouring the cell based on row index and column index from one Dataframe in another? Commented Nov 20, 2017 at 12:28
  • Yes I would use the colors created by the background_gradient applied to B, and use those colors on A. Commented Nov 20, 2017 at 12:32
  • Is my answer what you are looking for ? Commented Nov 20, 2017 at 13:30

1 Answer 1

9

I don't see a different method other than altering the background_gradient code for transferring style from one dataframe to other i.e

import pandas as pd
import matplotlib.pyplot as plt  
from matplotlib import colors

def b_g(s, cmap='PuBu', low=0, high=0):
    # Pass the columns from Dataframe A 
    a = A.loc[:,s.name].copy()
    rng = a.max() - a.min()
    norm = colors.Normalize(a.min() - (rng * low),
                        a.max() + (rng * high))
    normed = norm(a.values)
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
    return ['background-color: %s' % color for color in c]

B.style.apply(b_g,cmap='PuBu')

Output :

Dataframes

Hope it helps

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

4 Comments

Thanks Barath. I imagined it was going to be the way to do it. Thanks for showing the code to get that. Regards
Anyway to save styler objects to a png/pdf?
@thomas.mac I dont think we can save styler objects to a png. The answer is like applying the style on a different dataframe and return the style so the same is applied in the new dataframe. The solution only works if the shape of both is equal.
hi @Bharath, how do i modify your code to the effect of "axis=None", as above code shade column-wise. Thanks!

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.