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

Dash运行时更新scatter.children出现回调错误及KeyError 'Hours'问题求助

问题根源

Dash应用首次加载时会自动触发所有回调函数。你的patient-selector下拉框初始默认值设为none,此时update_output函数内的三个条件分支都不会命中,patient是预先定义的空DataFrame,空DataFrame不存在Hours列,自然触发KeyError。
后续手动选择R1/R2/R3后,patient被正确赋值,图表能正常显示,但首次加载触发的报错已经被记录,所以会一直看到报错提示。

解决方案
  • 方案1:修改下拉框初始默认值,直接指定有效患者
    把Dropdown配置里的value='none'改成value='R1',首次加载时就会命中R1的分支,patient有正确数据,不会触发空DataFrame取值问题。
dcc.Dropdown(
    id='patient-selector',
    options=[
        {'label': 'R1', 'value': 'R1'},
        {'label': 'R2', 'value': 'R2'},
        {'label': 'R3', 'value': 'R3'}
    ],
    value='R1', # 修改此处
    placeholder='Patient',
    style=dict(
        width='40%',
        horizontalAlign='right',
        color='blue'
    )
)
  • 方案2:在回调函数里增加无效值判断
    如果value不在合法取值范围内,直接返回提示文本,不执行绘图逻辑,避免空DataFrame取列报错:
@app.callback(
    Output('scatter', 'children'),
    [Input('patient-selector', 'value')])
def update_output(value):
    # 新增无效值判断
    if value not in ['R1','R2','R3']:
        return "请先选择一位患者查看数据"
    patient = pd.DataFrame()
    if value == 'R1':
        patient = df_percent.iloc[0:6]
    elif value == 'R2':
        patient = df_percent.iloc[6:12]
    elif value == 'R3':
        patient = df_percent.iloc[12:18]
    return dcc.Graph(id='scatter1',
                        figure={
                            'data': [
                                {
                                    'x': patient['Hours'],
                                    'y': patient['pct_Lymphs'],
                                    'type': 'line',
                                    'text':patient['Name'],
                                    'hoverinfo': 'text + y + x'
                                    }
                            ],
                            'layout': go.Layout(title='Patient Data',
                                                xaxis={'title': 'time'},
                                                yaxis={'title': 'percent'},
                                                hovermode='closest')
                        }
                     )
  • 方案3:禁止回调首次自动触发
    如果不需要默认显示图表,可以给回调添加prevent_initial_call=True参数,跳过应用加载时的自动回调:
@app.callback(
    Output('scatter', 'children'),
    [Input('patient-selector', 'value')],
    prevent_initial_call=True # 新增该行
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:27:01