熊猫风格背景渐变行和列

新手上路,请多包涵

添加背景渐变的 pandas 样式选项 非常适合快速检查我的输出表。但是,它是按行或按列应用的。是否可以一次将其应用于整个数据框?

编辑:一个最小的工作示例:

 df = pd.DataFrame([[3,2,10,4],[20,1,3,2],[5,4,6,1]])
df.style.background_gradient()

原文由 Peter9192 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 380
2 个回答

目前,您不能像 Nickil Maveli 指出的那样同时为行/列设置 background_gradient 。诀窍是自定义 pandas 函数 background_gradient

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

def background_gradient(s, m, M, cmap='PuBu', low=0, high=0):
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                            M + (rng * high))
    normed = norm(s.values)
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
    return ['background-color: %s' % color for color in c]

df = pd.DataFrame([[3,2,10,4],[20,1,3,2],[5,4,6,1]])
df.style.apply(background_gradient,
               cmap='PuBu',
               m=df.min().min(),
               M=df.max().max(),
               low=0,
               high=0.2)

原文由 Guilherme Beltramini 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 axis=None 摆脱调用中的最小和最大计算:

 def background_gradient(s, m=None, M=None, cmap='PuBu', low=0, high=0):
    print(s.shape)
    if m is None:
        m = s.min().min()
    if M is None:
        M = s.max().max()
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                            M + (rng * high))
    normed = s.apply(norm)

    cm = plt.cm.get_cmap(cmap)
    c = normed.applymap(lambda x: colors.rgb2hex(cm(x)))
    ret = c.applymap(lambda x: 'background-color: %s' % x)
    return ret

df.style.apply(background_gradient, axis=None)

编辑:您可能需要使用 normed = s.apply(lambda x: norm(x.values)) 才能在 matplotlib 2.2 上工作

原文由 Andreas Mueller 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题