Dashboard with multiple filters on the same Data Table

Hi
I have Dashboard which uses data from Pandas df. It is one table on which I want to provide 2 filters. One for COUNTRY, second for STATE. Below is a code (only problematic part shown) which I am using:

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)

With below code my Dashboard displays correctly but when I chose value for first filter i.e. COUNTRY it crashes with error:

Callback error updating table-container.children
TypeError: can only join an iterable

Can anyone help to point where is an error?

I figured it out. Function display_table needs to be changed to this:

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)
1 Like