You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bokeh DataTable行间单元格对比:高亮与首行差异单元格的问题

解决Bokeh DataTable高亮与首行不同单元格的问题

需求:在Bokeh DataTable中,将第1行的每个单元格与其他所有行的对应单元格对比,高亮值不同的单元格。

原代码可运行但结果不正确,核心问题是将首行所有值存入统一列表,未针对具体列匹配对应参考值,导致判断逻辑错误。

修正后的代码

import pandas as pd

from bokeh.models import HTMLTemplateFormatter, DataTable, TableColumn
from bokeh.plotting import show, output_notebook
output_notebook()

df = pd.DataFrame({'x':[1,2,3,1], 'y':[2,2,2,3]})

def get_html_formatter(reference_val):
    # 当单元格值与列首行参考值不同时,设置红色背景
    template = """        
        <div style="background:<%=
            (function colorfromint() {
                return value !== %s ? 'red' : '';
            }()) %>; 
            color: black"> 
        <%= value %>        
        </div>
    """ % reference_val

    return HTMLTemplateFormatter(template=template)

# 遍历每一列,为列配置对应首行参考值的格式化器
table_columns = []
for col in df.columns:
    # 获取当前列首行的参考值
    ref_val = df.iloc[0][col]
    formatter = get_html_formatter(ref_val)
    table_columns.append(TableColumn(field=col, title=col, formatter=formatter))

table = DataTable(source=df, columns=table_columns)
show(table)

关键改动说明

  • 针对每个列单独提取对应首行的参考值,而非传递整行的所有值,确保对比的是同列的单元格。
  • 简化模板中的判断逻辑:直接对比当前单元格的value与该列参考值,不等则设置红色背景,逻辑更精准。
  • 优化代码结构,清晰对应列与参考值的绑定关系,避免原代码中跨列判断的错误。

内容的提问来源于stack exchange,提问作者fssnag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 11:55:33