【问题标题】:Rendering a pandas dataframe to html, highlighting specific elements将 pandas 数据框渲染为 html,突出显示特定元素
【发布时间】:2020-04-17 19:32:14
【问题描述】:

我无法将 pandas 数据框渲染为 html,然后突出显示某些元素。

我有两个要渲染到 html 的 pandas 数据帧:

import pandas as pd
import webbrowser

data1 = [1, 2, 3, 4, 5]
data2 = [10, 20, 30, 40, 50]

data3 = [1, 2, 6, 4, 5]
data4 = [10, 21, 30, 40, 51]       

#make df1
df1 = pd.DataFrame(columns = ['data', 'points'])
df1['data'] = data1 
df1['points'] = data2 

#make df2
df2 = pd.DataFrame(columns = ['data', 'points'])
df2['data'] = data3
df2['points'] = data4

#render df1
html = df1.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("df1 Parameters \n" + html)
text_file.close()

#render df2
html = df2.to_html()
path = "C:\\path"
file_name = "file.html" 
text_file = open(file_name, "a+")
text_file.write("df1 Parameters \n" + html)
text_file.close()
webbrowser.open_new_tab(file_name)

这会在 html 文件中生成下表:

然后目标是比较 df1 和 df2 中的每个数据框元素,以查看它们是否相等或不同。相同的元素应以绿色突出显示,不匹配的元素应以红色突出显示。最终结果将是一个显示彩色数据框的 html 文件,如下所示:

【问题讨论】:

    标签: python html pandas


    【解决方案1】:

    让我们试试吧:

    import pandas as pd
    import webbrowser
    
    data1 = [1, 2, 3, 4, 5]
    data2 = [10, 20, 30, 40, 50]
    
    data3 = [1, 2, 6, 4, 5]
    data4 = [10, 21, 30, 40, 51]       
    
    #make df1
    df1 = pd.DataFrame(columns = ['data', 'points'])
    df1['data'] = data1 
    df1['points'] = data2 
    
    #make df2
    df2 = pd.DataFrame(columns = ['data', 'points'])
    df2['data'] = data3
    df2['points'] = data4
    
    df_style = df1 == df2
    
    def add_background(s):
        is_diff = df_style[s.name]
        return ['background-color: green' if v else 'background-color: red' for v in is_diff]
    
    
    
    #render df1
    html = df1.style.apply(add_background).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("df1 Parameters \n" + html)
    text_file.close()
    
    #render df2
    html = df2.style.apply(add_background).render()
    path = "C:\\path"
    file_name = "file.html" 
    text_file = open(file_name, "a+")
    text_file.write("df1 Parameters \n" + html)
    text_file.close()
    webbrowser.open_new_tab(file_name)
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 2017-04-01
      • 2021-06-12
      • 2021-07-16
      • 2022-10-06
      • 2014-07-30
      • 2022-12-12
      相关资源
      最近更新 更多