Updating displayed data frames based on user input

I’m very new to Dash so this question might be pretty simple, but I’m having a hard time finding resources on using data frames in Dash.

The first thing that I want to do is update a displayed data frame based on user input into a radio item (or maybe a dropdown menu), but I’m getting an error. Here’s an example below. I’m getting a callback error updating table_data.data.

from dash import Dash, html, dash_table, dcc, Input, Output
import pandas as pd
import numpy as np
import random

df = pd.DataFrame({
    'Region': ['USA', 'EU', 'ASIA']*4,
    'Feature': ['a', 'b']*6,
    'Amount': [random.randint(1,10) for val in range(12)]

app = Dash(__name__)

app.layout = html.Div([

        dash_table.DataTable(id="table_data", data = df.to_dict('records'), columns = [{"name": i, "id": i} for i in df.columns])



    Output('table_data', 'data'),
    Input('regions-radio', 'value'))
def set_cities_options(region_val):
    temp = df[df['Region']==region_val]
    return temp

if __name__ == '__main__':

Hello @Flume,

Instead of returning a dataframe, you need to return a dictionary.

Something like this:

return temp.to_dict('records')

Also, when posting code, please remember to use the </> button at the top of text area to make it easier to read, and also the ability to copy it.

1 Like

Thank you! And fixed the format so it can be copied. Thanks for the advice.

Do you know if there is a way to easily display the entire dataframe on first load before a selection on the region is made? When I loaded it there is no dataframe visible until a radio item is chosen.

1 Like

Sure, add this to the callback:


However, if you want to clear the dropdown and show all the data:

    Output('table_data', 'data'),
    Input('regions-radio', 'value'),
def set_cities_options(region_val):
    if region_val:
        temp = df[df['Region']==region_val]
        temp = df
    return temp.to_dict('records')
1 Like

Awesome thank you! Really appreciate it

1 Like