Pandas式背景渐变行和列

2024-05-14 14:23:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

编辑:最小工作示例:

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

Tags: 数据编辑示例dataframepandasdfstylepd
2条回答

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

编辑:您可能需要对this to work on matplotlib 2.2使用normed = s.apply(lambda x: norm(x.values))

当前不能同时为这两行/列设置background_gradient,如Nickil Maveli所指。诀窍是定制pandas function 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)

相关问题 更多 >

    热门问题