Python:仪表板在同一数据表上具有多个过滤器

时间:2020-05-11 05:14:17

标签: python plotly-dash

我有Dashboard,它使用了来自熊猫df的数据。我要在此表上提供2个过滤器。一个用于COUNTRY,第二个用于STATE。下面是我正在使用的代码(仅显示有问题的部分):

app.layout = html.Div(children=[
    html.H4(children='STATISTICS FOR COUNTRY AND STATE'),
    dcc.Dropdown(id='dropdown_country', options=[
        {'label': i, 'value': i} for i in stats_df.COUNTRY.unique()
    ], multi=True, placeholder='Filter by COUNTRY...'),
    dcc.Dropdown(id='dropdown_state', options=[
        {'label': i, 'value': i} for i in stats_df.STATE.unique()
    ], multi=True, placeholder='Filter by STATE...'),
    html.Div(id='table-container')
])

@app.callback(
    dash.dependencies.Output('table-container', 'children'),
    [dash.dependencies.Input('dropdown_country', 'value'), dash.dependencies.Input('dropdown_state', 'value')])

def display_table(dropdown_country, dropdown_state):
    if dropdown_country is None and dropdown_state is None:
        return generate_table(stats_df)

    stats_dff = stats_df.loc[(stats_df.COUNTRY.str.contains('|'.join(dropdown_country))) | (stats_df.STATE.str.contains('|'.join(dropdown_state)))]
    return generate_table(stats_dff)

使用以下代码,我的仪表板可以正确显示,但是当我选择第一个过滤器的值(即COUNTRY)时,它崩溃并显示错误:

回调错误更新table-container.children TypeError:只能 加入一个可迭代的

任何人都可以帮助指出错误在哪里吗?只需弄清楚一个过滤器(COUNTRY或STATE)都可以。

1 个答案:

答案 0 :(得分:0)

我知道了。功能display_table需要更改为此:

def display_table(dropdown_country, dropdown_state):
    if dropdown_country is None and dropdown_state is None:
        return generate_table(stats_df)
    if dropdown_country is not None and dropdown_state is not None:
        stats_dff = stats_df.loc[(stats_df.COUNTRY.str.contains('|'.join(dropdown_country))) & (stats_df.STATE.str.contains('|'.join(dropdown_state)))]
        return generate_table(stats_dff)
    if dropdown_country is not None:
        stats_dff = stats_df.loc[stats_df.COUNTRY.str.contains('|'.join(dropdown_country))]
        return generate_table(stats_dff)
    if dropdown_state is not None:
        stats_dff = stats_df.loc[stats_df.STATE.str.contains('|'.join(dropdown_state))]
        return generate_table(stats_dff)