Pandas - Style - Background Gradient using other dataframe

℡╲_俬逩灬. 提交于 2021-02-04 18:08:52

问题


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.


回答1:


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 :

Hope it helps



来源:https://stackoverflow.com/questions/47391948/pandas-style-background-gradient-using-other-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!