条件格式化 Pandas 数据框中的多列并保存为 HTML 以用于电子邮件

Conditional formatting Multiple Columns in Pandas Data Frame and saving as HTML for emailing

我有两个问题:

  1. 我需要有条件地格式化数据框的 2 个不同列
  2. 此数据框应另存为 html 用于应用格式的电子邮件正文

下面是我的数据框的样本集:

df = pd.DataFrame([
   ['item 1', 96, 12],
   ['item 2', 90, 23],
   ['item 3', 92, 17]
], columns = list("ABC"))

我要格式化单元格背景

在 Col B 中如下所示: 橙色:如果单元格值 >=95 蓝色:如果单元格值 <=90

在 C 栏中如下: 绿色:如果单元格值 <=15 红色:如果单元格值 >20

如果不满足条件(白色背景)则没有颜色可以放置

对数据框进行样式化/格式化后,我现在需要将这个带有颜色的数据框保存到 HTML 文件中,我将在电子邮件正文中使用该文件。我如何使用应用的格式将 df 导出到 html。

相同的代码是什么?

我不知道如何应用样式/到目前为止我所做的一切,我无法在 eclipse 中看到结果

下面是一些我试过但失败的代码:

import pandas as pd
def color_negative_red(value):
    if value >= 95:
        color = 'font-weight: bold; background-color: orange'
    elif value < 90:
        color = 'font-weight: bold; background-color: blue'
    return color

df = pd.DataFrame([
   ['item 1', 96, 12],
   ['item 2', 90, 23],
   ['item 3', 92, 17]
], columns = list("ABC"))

styled_df=df.style.apply(color_negative_red, subset=['B','C'])#.format({'B': "{:.2%}"})
df.to_html(r'd:\test.html')
print(styled_df.render())

我找到了解决方法如下:

import pandas as pd
df = pd.DataFrame([
   ['item 1', 96, 12],
   ['item 2', 90, 23],
   ['item 3', 92, 17]
], columns = list("ABC"))



df_styled=df.style.apply(lambda x: ["background: orange" 
                                    if (colname=='B' and value >= 95 ) 
                                    else  "background: blue" 
                                    if (colname=='B' and value<=90) 
                                    else "background: green" 
                                    if (colname=='C' and value<=15)
                                    else "background: orange"
                                    if (colname=='C' and value>=20)
                                    else ""
                                    for colname,value in x.iteritems()], axis = 1)
df_styled.to_html(r'd:\test_styled.html')