pandas 行和列的熊猫风格背景渐变

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38931566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:48:49  来源:igfitidea点击:

pandas style background gradient both rows and columns

pythonpandas

提问by Peter9192

The pandas style optionto add a background gradient is great for quickly inspecting my output table. However, it is applied either row-wise or columns-wise. Would it be possible to apply it to the whole dataframe at once?

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

EDIT: A minimum working example:

编辑:最低工作示例:

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

回答by Guilherme Beltramini

Currently you can't set the background_gradientfor both the rows/columns simultaneously as pointed by Nickil Maveli. The trick is to customize the pandas function background_gradient:

目前,您不能background_gradientNickil Maveli指出的那样同时设置两个行/列。诀窍是自定义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)

回答by Andreas Mueller

You can use axis=Noneto get rid of the min and max computations in the call:

您可以使用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)

Edit: You may need to use normed = s.apply(lambda x: norm(x.values))for this to work on matplotlib 2.2

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