我在将 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 文件中生成下表:
然后,目标是比较 df1 和 df2 中的每个数据框元素,看看它们是否相等或不同。相同的元素应以绿色突出显示,不匹配的元素应以红色突出显示。最终结果将是一个显示彩色数据框的 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 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)
输出: