我想根据其列有条件地格式化具有多个条件的 df,如下所示:
业务_实体 | 2021-H1 | 2022-H1 | 2022-H2 | 运动 | |
---|---|---|---|---|---|
2 | ABC | 0 | 0 | 100 | 100 |
4 | 防御 | 99 | 99 | 100 | 1 |
8 | GHI | 97 | 97 | 98 | 1 |
20 | JKl | 98 | 98 | 98 | 0 |
3 | 移动网络运营商 | 98 | 97 | 98 | 1 |
23 | PQR | 0 | 0 | 98 | 98 |
19 | STU | 98 | 97 | 98 | 1 |
22 | VWX | 96 | 98 | 98 | 0 |
17 | DFD | 97 | 99 | 98 | -1 |
我想做的是使用以下标准格式化 df:
对于 2021 年上半年到 2022 年下半年的专栏: 如果值 >= 89(绿色),如果值 >= 79.5 且 <89 (orange), and if value <79.5 (red)
对于“运动”栏: 如果值 >=.05(绿色),则值 >-.05 且 <.05 (orange), and value <=-.05 (red)
我在这里做了一些研究并提出了以下代码:
division_summary_table.style.apply(
lambda x: ['background:green'
if (colname=='2021-H1' and value >=89)
else 'background:orange'
if (colname=='2021-H1' and value >=79.5)
else 'background:red'
if (colname=='2021-H1' and value <79.5)
else 'background:green'
if (colname=='2022-H1' and value >=89)
else 'background:orange'
if (colname=='2022-H1' and value >=79.5)
else 'background:red'
if (colname=='2022-H1' and value <79.5)
else 'background:green'
if (colname=='2022-H2' and value >=89)
else 'background:orange'
if (colname=='2022-H2' and value >=79.5)
else 'background:red'
if (colname=='2022-H2' and value <79.5)
else 'background:green'
if (colname=='Movement' and value >=.5)
else 'background:orange'
if (colname=='Movement' and value >=0)
else 'background:red'
if (colname=='Movement' and value <-.5)
else ' '
for colname, value in x.items()],axis=1).format(precision=0)
目前工作正常,但确实“冗长”。由于我需要生成多个这样的表并应用相同的格式,因此我尝试编写一个简单的函数,然后稍后重用它:
def styler(df):
for colname, value in df.items():
if (colname=='2021-H1' and value >=89):
return 'background:green'
elif (colname=='2021-H1' and value >=79.5):
return 'background:orange'
elif (colname=='2021-H1' and value <79.5):
return 'background:red'
else:
return ''
division_summary_table.apply(styler)
当我应用它时,出现以下错误:
“函数
导致 应用方法折叠为系列”。通常,这是以下结果 该函数返回单个值,而不是类似列表。
我是初学者,真的不知道如何解决它。感谢您关于更好的方法来实现我想要实现的目标的建议。我需要帮助的另一件事是如何使用条件格式将表格保存为 png 文件。
让我们为
colorize
列子集定义函数:
def colorize_year(v):
return np.select(
[v >= 89, (v < 89) & (v >= 79.5), v < 79.5],
['background: green', 'background: orange', 'background: red']
)
def colorize_movement(v):
return np.select(
[v >= .05, (v < .05) & (v >= -.05), v <= -.05],
['background: green', 'background: orange', 'background: red']
)
(
df.style
.apply(colorize_movement, subset=['Movement'])
.apply(colorize_year, subset=['2021-H1', '2022-H1', '2022-H2'])
)
结果