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

Plotly Dash通过回调设置DataTable列名及数据不显示问题咨询

问题解决方案

核心问题定位

  • 你的DataTable没有定义columns参数,Dash无法识别需要渲染的列结构,这是表为空的核心原因
  • 由于你的列(日期字段)会随输入的Account动态变化,不能静态写死columns,需要将columns也加入回调的输出项
  • 原有数据处理逻辑中,pivot后category作为索引,转dict的时候会丢失分类列,导致缺少第一列展示维度

修正后的完整代码

import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash_table import DataTable
from dash.dependencies import Input, Output

df = pd.DataFrame([['1', '2021-01-31', 'category_1', 20],
                   ['1', '2021-01-31', 'category_3', 12],
                   ['1', '2021-02-28', 'category_1', 35],
                   ['1', '2021-02-28', 'category_2', 17],
                   ['1', '2021-02-28', 'category_3', 35],
                   ['1','2021-03-31', 'category_1', 12],
                   ['1','2021-03-31', 'category_2', 58],
                   ['1','2021-03-31', 'category_3', 23],
                   ['2', '2021-01-31', 'category_1', 29],
                   ['2', '2021-01-31', 'category_2', 66],
                   ['2', '2021-01-31', 'category_3', 22],
                   ['2', '2021-02-28', 'category_1', 53],
                   ['2', '2021-02-28', 'category_2', 71],
                   ['2', '2021-02-28', 'category_3', 32],
                   ['2','2021-03-31', 'category_1', 19],
                   ['2','2021-03-31', 'category_2', 2],
                   ['2','2021-03-31', 'category_3', 99],
                   ['3', '2021-02-28', 'category_1', 53],
                   ['3', '2021-02-28', 'category_2', 71],
                   ['3','2021-03-31', 'category_1', 19],
                   ['3','2021-03-31', 'category_2', 2],
                   ['3','2021-03-31', 'category_3', 99],
                   ['3','2021-03-31', 'category_4', 39]],
                   columns=['Account', 'Date', 'category', 'Amount'])


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    dcc.Input(id="account", type="string", placeholder="Enter Account"),
    DataTable(id='figure_1',
        style_cell_conditional=[{'if': {'column_id': c}, 'textAlign': 'center'} for c in ['category', '2021-01-31', '2021-02-28', '2021-03-31']],
        style_as_list_view=True,
        fill_width=True,
        style_cell={'font-size': '12px'},
        style_table={'height': '395px', 'overflowY': 'auto'})
])
                                       

@app.callback(
    [Output('figure_1', 'data'),
     Output('figure_1', 'columns')],
    [Input('account', 'value')]
)
def update_table(account):
    # 输入为空时返回空表
    if not account:
        return [], []
    # 筛选+聚合+透视
    df_query = df[df['Account'] == account].copy()
    df_pivot = df_query.groupby(['category', 'Date'])['Amount'].sum().unstack(fill_value=0).reset_index()
    # 生成列配置
    columns = [{'name': col, 'id': col} for col in df_pivot.columns]
    # 转换为DataTable要求的格式
    data = df_pivot.to_dict(orient='records')
    return data, columns


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

关键修改说明

  • 回调新增了columns输出项,会根据当前查询到的日期动态生成列配置,不需要提前写死
  • 重构了数据透视逻辑,将category保留为普通列,作为第一列展示分类维度
  • 增加了空输入的兼容逻辑,避免初始加载时报错
  • 调整了style_cell_conditional的匹配规则,从索引匹配改为列名匹配,适配动态列的样式控制
  • 如果需要隐藏表头,在DataTable配置中补回style_header={'display': 'none'}参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:18:01