如何将 background_gradient 应用于 pandas 数据框列中的前 n 个最大值?

问题描述 投票:0回答:2
专栏1 专栏2
1 222
3 4
11 21414
12 33
113 123

最近发现pandas dataframes formatting,遇到如下问题: 我希望上表看起来像下图,如果 n = 3:Formatted table

我没有找到这个用例的 style.background_gradient*()* 方法的应用。我试过 highlight_max(),但它每列只格式化 1 个单元格。

谢谢!

python pandas formatting max gradient
2个回答
1
投票

您可以按照 文档

中的说明使用 Styler 对象

尝试以下操作:

from IPython.display import display #I assume you are in a notebook

_min = df.values.min() #white value
_max = df.values.max() #darkest blue value

df = df.style.background_gradient(axis=None, vmin=_min, vmax=_max, cmap="Blues")
display(df)

如果你想每列有不同的比例,只需省略设置

vmin
vmax
值。

df.style.background_gradient(cmap="Blues")

这里是可用的彩色地图列表


1
投票

这在style user guide中有很好的描述。

使用

style.background_gradient

import seaborn as sns

cm = sns.light_palette('blue', as_cmap=True)

df.style.background_gradient(cmap=cm)

输出:

如您所见,输出与您的预期有点不同:

expected output

然而,您可以使用非线性比例,例如通过使用

gmap
传递日志值,并解压缩低值(
low
参数)。

import numpy as np

df_log = np.log(df)

df.style.background_gradient(gmap=df_log.div(df_log.max()),
                             low=-0.3, cmap=cm, axis=None)

输出:

© www.soinside.com 2019 - 2024. All rights reserved.