简体   繁体   中英

filtering pd.DataFrame with dash dropdown

I'm new to Dash and trying to filter the the following dataframe with a dropdown and show the filter dataframe. I am not able to define the callback function properly. Any sample code is really appreciated,

df = pd.DataFrame({
    'col1': ['A', 'B', 'B', 'A', 'B', 'A'],
    'col2': [2, 1, 9, 8, 7, 4],
    'col3': [0, 1, 9, 4, 2, 3],   
})  

Here is the page from the docs that I think might be a good place to start. If you know the dataframe ahead of time, then you can populate the dropdown with the values that you know you'll need. If you don't, then you would need to use a callback to update the dropdown options prop.

The first example on that docs page shows how to get the value from a dropdown, and output it. In your case, you'd use the dropdown to filter the dataframe perhaps like:

@app.callback(
    Output('data-table-id', 'data'),
    [Input('dropdown-id', 'value')
)
def callback_func(dropdown_value):
    df_filtered = df[df['col1'].eq(dropdown_value)]

    return df_filtered.to_dict(orient='records)

And then you would set the output of the callback to the data prop of a Dash datatable. I've added some made-up values for the Output and Input part of the dropdown, hopefully that gives the general idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM