将pandas数据框渲染为html,突出显示特定元素

时间:2019-12-28 01:04:52

标签: python html pandas

我在将pandas数据框呈现为html然后突出显示某些元素时遇到了麻烦。

我有两个要渲染为html的熊猫数据框:

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文件中生成下表:

enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:0)

让我们尝试一下:

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)

输出:

enter image description here