我编写了以下代码块来为数据框中的一些单元格着色。
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
这是随机数据的结果:
关于Pandas Styling - 对特定列的单元格而不是整个 DataFrame 进行着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60175045/