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

在函数中格式化Dash DataTable并返回至布局时出现加载错误

问题分析与修复

你的代码里有几个关键错误导致了「Error Loading layout」:

错误1:DataTable的data参数格式错误

Dash DataTable的data参数需要接收字典列表(DataFrame的records格式),而不是直接传入DataFrame对象。原代码里data=styled_df不符合要求,必须转换成字典列表格式。

错误2:列配置重复且逻辑冗余

原代码里indexName = styled_df.reindex().columns[0]完全多余,拼接columns时还会重复添加第一列,导致列定义冲突,直接基于所有列生成配置即可。

错误3:filter_query的字符串转义错误

style_data_conditional里的filter_query需要用{列名}的格式,但f-string里直接写{col}会被解析成变量,必须用{{{col}}}转义大括号,生成正确的查询格式;另外Python字符串里不需要用&lt;,直接写<就行。

错误4:列类型设置错误

原代码给所有列都设置type='numeric',但Name列是字符串类型,强制设为数值型会导致渲染错误,应该只对数值列设置该类型。


修复后的完整代码

import dash
from dash import html, dash_table
import pandas as pd

def styletable(dataframe):
    styled_df = dataframe.copy()

    # 生成列配置:区分数值列和非数值列
    columns = []
    for col in styled_df.columns:
        col_config = {'name': col, 'id': col}
        # 仅对数值类型列设置type='numeric'
        if pd.api.types.is_numeric_dtype(styled_df[col]):
            col_config['type'] = 'numeric'
        columns.append(col_config)

    styled_table = dash_table.DataTable(
        columns=columns,
        data=styled_df.to_dict('records'),  # 修正data参数格式
        style_data_conditional=[
            {
                'if': {'column_id': col, 'filter_query': f'{{{col}}} < 0'},
                'color': 'red'
            }
            # 仅对数值列应用条件样式,避免字符串列报错
            for col in styled_df.columns if pd.api.types.is_numeric_dtype(styled_df[col])
        ],
        style_header={'fontWeight': 'bold'}
    )
    return styled_table


app = dash.Dash()

df = pd.DataFrame({
    'Name': ['John Doe', 'Jane Doe', 'Mary Smith', 'Peter Jones'],
    'Age': [30, 25, 40, 35],
    'Salary': [50000, 40000, 60000, 55000]
})

styled_table = styletable(df)

app.layout = html.Div([styled_table])

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:17:02