I’ve been struggling with to create an filter that let me have selected_rows displayed in another table. I’m using this code
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from dash.dependencies import Input, Output, State
from dash_table import DataTable
#Define sample dataframes with the same columns
df1 = pd.DataFrame({'Category': ['A', 'B', 'C'], 'Value': [1, 2, 3], 'tipo': ['Direita','Esquerda','Direita']})
df2 = pd.DataFrame({'Category': ['D', 'E', 'F'], 'Value': [5, 6, 7], 'tipo': ['Esquerda','Direita','Esquerda']})
lista_filtros = df1['tipo'].unique()
# Define Dash app
app = dash.Dash(__name__)
app.config.suppress_callback_exceptions = True
# Define dropdown options
dropdown_options = [{'label': 'Dataframe 1', 'value': 'df1'},
                    {'label': 'Dataframe 2', 'value': 'df2'}]
# Define layout
app.layout = html.Div([
    dcc.Dropdown(
        id='dropdown',
        options=dropdown_options,
        value='df1'
    ),
    dcc.Checklist(
        id='type-checklist',
        options=[{'label': i, 'value': i} for i in lista_filtros] + [{'label': 'All', 'value': 'All'}],
        value=['All']
    ),
    html.Br(),
    DataTable(
        id='table',
        row_selectable='multi',
        selected_rows=[],
        page_size=15
    ),
    html.Button('Submit', id='submit-button', n_clicks=0),
    dcc.Store(id='selected-rows', storage_type='session'),
    html.Br(),
    html.Div([
        DataTable(
            id='selected-data',
            columns=[{'name': 'Category', 'id': 'Category'}, {'name': 'Value', 'id': 'Value'}],
            page_size=5,
            row_deletable= True,
        )
    ], id='selected-data-container', style={'display': 'none'})
])
# Define callback to update table based on dropdown selection and type checklist
@app.callback(
    Output('table', 'data'),
    [Input('dropdown', 'value'), Input('type-checklist', 'value')]
)
def update_table(selected_value, selected_type):
    if selected_value == 'df1':
        df = df1
    elif selected_value == 'df2':
        df = df2
    else:
        return []
    all_selected = 'All' in selected_type
    if all_selected:
        return df.to_dict('records')
    else:
        filtered_df = df[df['tipo'].isin(selected_type)]
        # preserve original order of rows
        filtered_df = filtered_df.set_index('tipo')
        filtered_df = filtered_df.loc[selected_type]
        filtered_df = filtered_df.reset_index()
        return filtered_df.to_dict('records')
# Define callback to store selected rows in dcc.Store
@app.callback(
    Output('selected-rows', 'data'),
    [Input('submit-button', 'n_clicks')],
    [State('table', 'selected_rows')]
)
def store_selected_rows(n_clicks, selected_rows):
    if selected_rows:
        return selected_rows
# Define callback to update selected data table visibility and content
@app.callback(
    [Output('selected-data-container', 'style'),
     Output('selected-data', 'columns'),
     Output('selected-data', 'data')],
    [Input('selected-rows', 'data')],
    [State('selected-data', 'data'),
     State('dropdown', 'value')]
)
def update_selected_data(selected_rows, stored_data, selected_value):
    if selected_rows:
        # get selected rows from selected dataframe
        if selected_value == 'df1':
            selected_df = df1.iloc[selected_rows]
        elif selected_value == 'df2':
            selected_df = df2.iloc[selected_rows]
        else:
            selected_df = pd.DataFrame()
        # add new selected data to stored data
        if stored_data is not None:
            stored_df = pd.DataFrame(stored_data)
            stored_df = stored_df.append(selected_df, ignore_index=True)
            stored_data = stored_df.to_dict('records')
        else:
            stored_data = selected_df.to_dict('records')
        # get columns for selected data table
        selected_columns = [{'name': i, 'id': i} for i in selected_df.columns]
        # return updated values
        return {'display': 'block'}, selected_columns, stored_data
    else:
        # return default values
        return {'display': 'none'}, [], None
# Run the app
if __name__ == '__main__':
    app.run_server(debug=True)
The dashboard works well until I select a parameter other than “all” for my “selected_type” checklist.
This is because I am having issues with the index that the “selected_rows.data” parameter returns to me.
For example, if I use the filter “right”, what I will see is the “category = B”, which is index 0 of my “id = table” after being filtered.
However, when I press the “submit” button, my function uses index 0 in the original table before it was filtered, so I receive the data “Category = A”.
This is more of a Python problem than a Dash problem, but the use of callbacks has made it difficult for me to solve, resulting in various errors when I try to recreate a new filtered dataframe within the “updated_selected_data” function.
I just need my table to reflect exactly the data I am seeing in the previous table, and this can probably be done quite easily using any parameter other than the index. Any ideas on how I can solve this problem?




