熊猫样式:通过绝对值有条件地更改列的背景颜色

时间:2019-05-18 19:30:13

标签: python pandas colors pandas-styles

我有pandas数据框,我想根据绝对值给出背景渐变颜色,想象一下,我的期望值是数据框A列中的6。随着数字从期望值变化,背景渐变颜色在两个方向上都以绝对值相同(无论正向还是负向)变化。

下面的帖子用来结束我想要的内容,但是这些颜色不考虑绝对值。pandas style background gradient both rows and columns,还有熊猫文档http://pandas.pydata.org/pandas-docs/stable/user_guide/style.html

我创建了最小代码:

import pandas as pd

colum1 = [-1,0,1,2,3,4,5,6,7,8,9,10,11,12]

df = pd.DataFrame(data=colum1,columns=["A"])

我已经在Excel中创建了预期的输出作为图像。我想从代码中获得类似的输出。 background gradient change by absolute valye

1 个答案:

答案 0 :(得分:2)

我面临着类似的任务,经过一些“研究”,我找到了解决方案。

from matplotlib import colors
import seaborn as sns

def b_g(s):
    cm=sns.light_palette("red", as_cmap=True)
    max_val = max(s.max(), abs(s.min()))
    norm = colors.Normalize(0,max_val)
    normed = norm(abs(s.values))
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cm)(normed)]
    return ['background-color: %s' % color for color in c]

b_g函数可让您根据数据框数据生成自定义的colors_map,cm=sns.light_palette("red", as_cmap=True)可以帮助自定义颜色。

在数据框上应用此功能的过程如下:

dataframe.style.apply(b_g)

这里的窍门是在使用abs()函数计算来自数据帧的数据的赋范值时。 Example result

文档上的链接: https://seaborn.pydata.org/generated/seaborn.light_palette.html https://pandas.pydata.org/pandas-docs/version/0.18/style.html