-->

display datatable after filtering rows from dropdo

2020-05-06 12:54发布

问题:

I'm new to Dash. I would like to make a app, where I can select values from dropdown filter, filter dataset and display the data table. I'm using dash_table.

My example app code is below. No datatable is shown. Does anyone know what I did wrong? How can I render dash table in dash app?

import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_table as dt
from dash.dependencies import Input, Output
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')

app = dash.Dash(__name__)



states = df.State.unique().tolist()

app.layout = html.Div(
    children=[
    dcc.Dropdown(
            id='filter_dropdown',
            options=[{'label':st, 'value':st} for st in states],
            value = states[0]
            ),
    dt.DataTable(id='table-container') ]
)

@app.callback(
    Output('table-container', 'data'),
    [Input('filter_dropdown', 'value') ] )
def display_table(state):
    dff = df[df.State==state]
    return dff

if __name__ == '__main__':
    app.run_server(debug=True)

BTW, do anyone know where I can find collections of dash app gallery with code?

回答1:

You have to set the columns of your data table and return your dataframe as a dict in a special form. So change these two lines in your code to make it work.

dt.DataTable(id='table-container', columns=[{'id': c, 'name': c} for c in df.columns.values])

return dff.to_dict('records')

BTW, do anyone know where I can find collections of dash app gallery with code?

Best place with lots of examples with code is the Dash User Guide. You can for instance find the data table there.