Populate a dropdown from file upload

Dear Forum,
I’m currently learning how to use Dash and following the examples provided by the website. I’m looking for a way to dynamically populate a drop-down list after uploading a file (i.e. .csv); and perhaps I missed some examples of others who have done that. Essentially I’d like to filter the dataframe once the data has been uploaded.

so, below is the dcc call placed in Layout section of a Dash app. Assuming that we’ve followed the upload tutorial on this site, how does one go about referencing the uploaded dataframe and in the drop down?

     html.P("Select Product:", className="control_label"),
                        dcc.Dropdown(
                            id="product",
                            options=[{'label': i, 'value': i } for i in (how to reference a dataframe column here?)],
                            multi=False,

If you check the example from the documentation you will see how upload functions. The layout for the upload button will be more or less like this one:

    html.A(dcc.Upload(
        id='upload_data_button',
        children=html.Div([
            html.I(className="fas fa-upload"),
            '  Drag and Drop or Select Files'
        ]),
        # Allow multiple files to be uploaded or not
        multiple=False
    )),
    dcc,Dropdown(id='cool_dropdown'),

Then, again from the docs, you will find a “parse_uploads” (or something) function so all you have to do is returnto the options attribute of your dropdown, like:

@app.callback(Output('cool_dropdown', 'options'),
              [Input('upload_data_button', 'contents')],
              [State('upload_data_button', 'filename'),
               State('upload_data_button', 'last_modified')])
def parse_uploads(content, name, date):
    df = parse(contents, names)
    return [{'label': i, 'value': i } for i in df.columns]

Edit: Don’t remember the link. Anyhow, parse would be something like this:

def parse(contents, filename):
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)
    df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))

Thank you, I got it working!

Hello, Can you please provide me your working code. I have been struggling a lot with this. Thank you

1 Like