熊猫 - 样式 - 使用其他数据框的背景渐变

Tan*_*gne 6 python matplotlib pandas

我喜欢使用 background_gradient,因为它可以帮助我以 excel 的方式查看我的数据框。
但我想知道是否有办法将颜色映射到另一个数据框中的数字。
例如,我热衷于使用 zscores 的数据框为数据框着色,以便我可以快速查看异常值的值。

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(???)
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用background_gradient以便它使用数据帧 B 中的值来设置样式 A。

Flo*_*oor 9

除了更改background_gradient 代码以将样式从一个数据帧转移到另一个 ie之外,我没有看到其他方法

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')
Run Code Online (Sandbox Code Playgroud)

输出 :

数据帧

希望能帮助到你