将数据帧呈现为html,突出显示特定元素

2024-04-25 12:04:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在将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


Tags: to数据pathtextname元素datamake
1条回答
网友
1楼 · 发布于 2024-04-25 12:04:08

让我们试试:

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

相关问题 更多 >

    热门问题