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

Python Dash基于颜色DataFrame设置DataTable单元格背景色

解决方案

dash_table.DataTable组件的style_data_conditional属性支持按行索引+列ID精准定位单个单元格,你只需要提前遍历两个DataFrame,把每个单元格对应的颜色值封装成样式规则传入即可,不需要额外写回调,静态配置就能实现颜色一一匹配。

核心实现逻辑

  • 遍历业务DataFrame的每一行索引、每一列ID
  • 从颜色DataFrame中取出对应位置的十六进制颜色值
  • 为每个单元格生成独立的样式规则,匹配对应行列位置时应用对应背景色
  • (可选)根据背景色深浅搭配文字颜色,避免深色背景下文字看不清的问题

完整可运行代码

from dash import Dash, dash_table
import pandas as pd
from collections import OrderedDict

data = OrderedDict(
    [
        ("Date", ["2015-01-01", "2015-10-24", "2016-05-10", "2017-01-10", "2018-05-10", "2018-08-15"]),
        ("Region", ["Montreal", "Toronto", "New York City", "Miami", "San Francisco", "London"]),
        ("Temperature", [1, -20, 3.512, 4, 10423, -441.2]),
        ("Humidity", [10, 20, 30, 40, 50, 60]),
        ("Pressure", [2, 10924, 3912, -10, 3591.2, 15]),
    ]
)
df = pd.DataFrame(data)

data_color = OrderedDict(
    [
        ("Date", ["#26118f", "#ce1177", "#26118f", "#26118f", "#26118f", "#26118f"]),
        ("Region", ["#ce1177", "#26118f", "#ce1177", "#ce1177", "#ce1177", "#ce1177"]),
        ("Temperature", ["#ce1177", "#ce1177", "#26118f", "#ce1177", "#ce1177", "#ce1177"]),
        ("Humidity", ["#26118f", "#ce1175", "#ce1177", "#ce1177", "#ce1177", "#ce1177"]),
        ("Pressure", ["#cf1177", "#ce1173", "#ce1177", "#ce1177", "#ce1177", "#ce1177"]),
    ]
)
df_color = pd.DataFrame(data_color)

# 生成单元格样式规则
cell_style_rules = []
for row_id in range(len(df)):
    for col_name in df.columns:
        # 取对应位置的颜色值
        bg_color = df_color.loc[row_id, col_name]
        cell_style_rules.append(
            {
                "if": {"row_index": row_id, "column_id": col_name},
                "backgroundColor": bg_color,
                "color": "white"  # 深色背景配白字,不需要可以删掉这行
            }
        )

app = Dash(__name__)
app.layout = dash_table.DataTable(
    data=df.to_dict("records"),
    columns=[{"id": c, "name": c} for c in df.columns],
    style_data_conditional=cell_style_rules  # 传入样式规则
)

if __name__ == "__main__":
    app.run_server(debug=True)

注意事项

  • 该方案要求业务DataFrame和颜色DataFrame的列名完全一致、行顺序完全对应,你已经说明两个表行列尺寸完全匹配,只要满足列名对应就不会出现颜色错位。
  • 即使后续开启表格排序、筛选、分页功能,样式也会自动跟随对应数据单元格,不会出现错位,因为规则绑定的是数据行的逻辑索引,不是页面渲染的视觉行号。
  • 如果不需要给全量单元格设置颜色,只需要在遍历环节过滤对应的行、列即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 17:30:50