✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

How to populate a DropDown from unique values in a pandas data frame

So, I was able to adapt the example on generating an HTLM table from a Pandas dataframe. I now want to add a DropDown control to filter the table. I would like the DropDown to display unique values from a column in the table. I do not want to list the values into the options off the DropDown, but to get them from a dataframe that contains the list of unique values.

Once the user selects a value from the DropDown, the table would update to reflect filtering choice made by user.

Would something like this work? I recommend reading through the user guide https://plot.ly/dash/getting-started-part-2 to learn more about how these callbacks work.

import dash
import dash_core_components as dcc
import dash_html_components as html

import pandas as pd

df = pd.read_csv(
    'https://gist.githubusercontent.com/chriddyp/'
    'c78bf172206ce24f77d6363a2d754b59/raw/'
    'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'
    'usa-agricultural-exports-2011.csv')

def generate_table(dataframe, max_rows=10):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

app = dash.Dash()

app.layout = html.Div(children=[
    html.H4(children='US Agriculture Exports (2011)'),
    dcc.Dropdown(id='dropdown', options=[
        {'label': i, 'value': i} for i in 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', 'value')])
def display_table(dropdown_value):
    if dropdown_value is None:
        return generate_table(df)

    dff = df[df.state.str.contains('|'.join(dropdown_value))]
    return generate_table(dff)

app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})

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

3 Likes

Thanks for the example. Will take a look at the code and the callbacks documentation.

Thanks for the example: I have played with it and successfully added a frame around the table. But, I am not able to make it collapse, nor add shading to the even numbered rows. Additionally, I would like to add vertical/horizontal scroll bars as my app will display 15 rows and have many columns in the table.

Here is my code so far:
app.layout = html.Div(children=[
html.H4(children=’‘US Agriculture Exports (2011)’),
dcc.Dropdown(id=‘dropdown’, options=[
{‘label’: i, ‘value’: i} for i in df.SOR_NM.unique()
], multi=True, placeholder=‘Filter by state’),
html.Div(id=‘table-container’
, children=‘State detail’
, style={‘border’: ‘solid’, ‘border-collapse’:‘collapse’,
‘nth-child(even)’ : ‘#dddddd’} )
])

You’ll have to add this with either an external CSS stylesheet. The nth-child(even) doesn’t work for inlines styling unfortunately.

border-collapse does not make the component collapsable, it just specifies the spacing (see https://css-tricks.com/almanac/properties/b/border-collapse/). If this is indeed the property that you want to set, you’ll need to apply it on the Table component rather than the parent Div component.

Setting overflow-x and overflow-y to scroll along with a fixed width and height all inside the style attribute of the container Div or Table should so this for you.

Note that I’m also working on a more interactive table component, see the discussion here: Display tables in Dash

Thank you for the example, it was very helpful!
Is there any way I can make the table editable though?

hi there I ,have exactly copied the code and replaced it with my csv file ,that contains almost 600000 rows , though I click on a specific element , it doesn’t filter at all,can you please help me out with this

Yes, DataTable elements can be editable. Check out this guide: https://dash.plot.ly/datatable/editable
It will go into details for things like:

  • Letting user change data
  • Figuring out which cell as been changed
  • Changing other cells based on changed cells

Hope it helps

2 Likes

hey, thanks for the help, can i do that for a line chart? i have sales data i want to see the sales,profit and total items sold of selected products by dates. i am new to dash, can you help me out?