Pandas 样式 - 为特定列的单元格而不是整个 DataFrame 着色

Pandas Styling - Coloring cells of specific columns instead of entire DataFrame

我编写了以下代码块来为数据框中的一些单元格着色。

def applycolor(dtf):

        return ['background-color: lightgreen' if x >= 1500  else 
        ('background-color: lightskyblue' if 1000 <= x < 1500  else 
        'background-color: pink' if 750 <= x < 1000 else
        'background-color: wheat' if  550 <= x < 750 else 
        'background-color: paleturquoise' if 330 <= x < 550  else 
        'background-color: darkseagreen' if 150 <= x < 330 else 'background-color: default') for x in dtf]    


cs1 = cs.style.apply(applycolor, axis=0)

这给了我如图所示的结果。

但是,我只想为 df['$-Score'] 中指定的图形渲染颜色。但是这种样式将颜色附加到数据框的所有相关数字,如所见。

我试图更改列表理解的最后一行以仅包含数据框的特定列,如下所示:.....if 150 <= x < 330 else 'background-color: default') for x in dtf['$-Score']- 但它返回了一个错误。

已尝试寻找具体答案,但未能找到。有什么想法吗?

或者,示例数据框:

    A    B   C
0   83  76  30
1   34  17  44
2   72  16  94
3   24  94  27
4   98  36  35
5   41  77  39
6   65  54  18
7   85  1   59
8   12  79  2
9   33  57  76
10  66  69  100
11  99  51  89
12  24  74  32
13  51  98  63
14  63  36  82
15  53  52  65

我只想在 B 列中将 55 到 58 之间的数字标记为红色,在 C 列中将 84 到 87 之间的数字标记为蓝色。

我该怎么做?

Style.apply 的工作方式与 DataFrame.apply 一样,数据框被分成系列,在您的情况下,您希望根据每个系列的名称(即列名)做一些不同的事情。因此,可以根据您的目的扩展以下示例:

def apply_formatting(col):
    if col.name == 'a':
        return ['background-color: red' if c > 50 else '' for c in col.values]
    if col.name == 'b':
        return ['background-color: green' if c > 10 else '' for c in col.values]
    if col.name == 'c':
        return ['background-color: blue' if c > 30 else '' for c in col.values]

data = pd.DataFrame(
    np.random.randint(0, 100, 30).reshape(10, 3), columns=['a', 'b', 'c'])

data.style.apply(apply_formatting)  # axis=0 by default

这是随机数据的结果:

只需使用subset属性


df.style.apply(your_func, subset=['column_name'])