【问题标题】:rendering pandas dataframe ot html with highlighted cells使用突出显示的单元格将 pandas 数据帧渲染为 html
【发布时间】:2020-03-10 19:01:35
【问题描述】:

我有一个要渲染到 html 的 pandas daraframe:

df = pd.DataFrame()
df['parm A'] = [9.5, 8.2, 13]
df['parm B'] = [True, False, True]


html = df.to_html()
path = "C:\\path"
file_name = "file.html" #make file name specific to patient and plan name
text_file = open(file_name, "w")
text_file.write("df Parameters \n" + html)
text_file.close()

数据框包含浮点数和布尔值的组合。目标是使用一组条件呈现数据帧。在这个特定的数据框中,如果小于 10,浮点数将以绿色突出显示,如果大于 10,则以红色突出显示。此外,包含 True 的单元格将是绿色的,而 False 将是红色的:

【问题讨论】:

    标签: python html pandas


    【解决方案1】:

    一种解决方案是使用 pandas 样式,如下所示:

    import pandas as pd
    df = pd.DataFrame()
    df['parm A'] = [9.5, 8.3, 13]
    df['parm B'] = [True, False, True]
    
    def red_green(s):
        return ['background-color: green' if (v<10 and v) else 'background-color: red' for v in s]
    
    html = df.style.apply(red_green).render()
    path = "C:\\path"
    file_name = "file.html" #make file name specific to patient and plan name
    text_file = open(file_name, "w")
    text_file.write("df Parameters \n" + html)
    text_file.close() 
    

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 2021-06-12
      • 1970-01-01
      • 2021-06-01
      • 2011-07-30
      • 1970-01-01
      • 2021-07-03
      • 2020-09-01
      • 1970-01-01
      相关资源
      最近更新 更多