# Dropdown filtering for uploaded dataset

**URL:** https://community.plotly.com/t/dropdown-filtering-for-uploaded-dataset/21715
**Category:** Dash Python
**Created:** [April 1, 2019, 2:56pm UTC](https://community.plotly.com/t/dropdown-filtering-for-uploaded-dataset/21715 "2019-04-01T14:56:40Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![kasper\_pr3](https://avatars.discourse-cdn.com/v4/letter/k/c77e96/32.png) [@kasper\_pr3](https://community.plotly.com/u/kasper_pr3)
#### Post date: [April 1, 2019, 2:56pm UTC](https://community.plotly.com/t/dropdown-filtering-for-uploaded-dataset/21715/1 "2019-04-01T14:56:40Z")

</div>

Hello everyone

I am creating a dash app, that allows the user to upload a csv file using the dcc.upload function.

When the csv is uploaded I want to the user to be able to filter the dataset by a dropdown, such that he can choose some value the column “var\_name”. However, I am not sure how to access the uploaded dataset for filtering, I am only able to display the whole thing. Hope anyone can help. Here is my code:

import base64  
import datetime  
import io

import dash  
import dash\_table  
import dash\_core\_components as dcc  
import dash\_html\_components as html  
import pandas as pd  
from dash.dependencies import Input, Output, State

def df\_to\_table(df):  
return html.Table(  
# Header  
[html.Tr([html.Th(col) for col in df.columns])] +

```
    # Body
    [
        html.Tr(
            [
                html.Td(df.iloc[i][col])
                for col in df.columns
            ]
        )
        for i in range(len(df))
    ]
)

```

external\_stylesheets = [‘[https://codepen.io/chriddyp/pen/bWLwgP.css](https://codepen.io/chriddyp/pen/bWLwgP.css)’]

app = dash.Dash( **name** , external\_stylesheets=external\_stylesheets)

app.layout = html.Div([  
html.Div([  
dcc.Upload(  
id=‘upload-data’,  
children=html.Div([  
'Drag and Drop eller ',  
html.A(‘Vælg Fil’)  
]),  
style={  
‘width’: ‘100%’,  
‘height’: ‘60px’,  
‘lineHeight’: ‘60px’,  
‘borderWidth’: ‘1px’,  
‘borderStyle’: ‘dashed’,  
‘borderRadius’: ‘5px’,  
‘textAlign’: ‘center’,  
‘margin’: ‘10px’  
},  
# Allow multiple files to be uploaded  
multiple=True  
),  
html.Div(id=‘output-data-upload’)  
]),  
html.Div([

```
    html.Div([
        html.H1('Vælg variabel'),
        dcc.Dropdown(
            id='var-choice',
            options=[{'label': i, 'value': i} for i in df['var_name'].unique()],
            value='Variabel'
        )
    ],
    style={'width': '48%', 'display': 'inline-block'})
        ]),

```

html.Div(  
id=“my-table”,  
className=“row”,  
style={  
“maxHeight”: “350px”,  
“overflowY”: “scroll”,  
“padding”: “8”,  
“marginTop”: “5”,  
“backgroundColor”:“white”,  
“border”: “1px solid #C8D4E3”,  
“borderRadius”: “3px”  
},  
),  
# dash\_table.DataTable(  
# id=‘my-table’,  
# columns=[{“name”: i, “id”: i} for i in df.columns],  
# rows=df.to\_dict(“data”))

])

# show table from file upload

def parse\_contents(contents, filename, date):  
content\_type, content\_string = contents.split(’,’)

```
decoded = base64.b64decode(content_string)
try:
    if 'csv' in filename:
        # Assume that the user uploaded a CSV file
        df = pd.read_csv(
            io.StringIO(decoded.decode('utf-8')))
    elif 'xls' in filename:
        # Assume that the user uploaded an excel file
        df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
    print(e)
    return html.Div([
        'There was an error processing this file.'
    ])

return df, html.Div([
    html.H5(filename),
    html.H6(datetime.datetime.fromtimestamp(date)),

    dash_table.DataTable(
        data=df.to_dict('rows'),
        columns=[{'name': i, 'id': i} for i in df.columns],
        style_table={
                'maxHeight': '300',
                'overflowY': 'scroll'}
    ),

    html.Hr(), # horizontal line

    # For debugging, display the raw contents provided by the web browser
    html.Div('Raw Content'),
    html.Pre(contents[0:200] + '...', style={
        'whiteSpace': 'pre-wrap',
        'wordBreak': 'break-all'
    })
])

```

@app.callback(Output(‘output-data-upload’, ‘children’),  
[Input(‘upload-data’, ‘contents’)],  
[State(‘upload-data’, ‘filename’),  
State(‘upload-data’, ‘last\_modified’)])

def update\_output(list\_of\_contents, list\_of\_names, list\_of\_dates):  
if list\_of\_contents is not None:  
children = [  
parse\_contents(c, n, d) for c, n, d in  
zip(list\_of\_contents, list\_of\_names, list\_of\_dates)]  
return children

# update table based on dropdown’s value and df updates

@app.callback(  
Output(“my-table”, “children”),  
[Input(“var-choice”, “value”)]  
)  
def update\_table(status):  
# df = pd.read\_csv(‘data\_[PFA\_scaproc.txt]\_20190401\_114903.csv’)  
df = df[df[‘var\_name’] == status]

```
# df = df[["CreatedDate", "Status", "Company", "State", "LeadSource"]]
return df_to_table(df)

```

if **name** == ‘ **main** ’:  
app.run\_server(debug=True)
