gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:26 25 4
gpt4 key购买 nike

我在将 pandas 数据框渲染为 html 然后突出显示某些元素时遇到问题。

我有两个 pandas 数据框,我正在将它们渲染为 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

最佳答案

让我们尝试一下:

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

关于python - 将 pandas 数据框渲染为 html,突出显示特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com