Hello,
I was wondering if there is a good way to read in a CSV file into a dictionary for a dcc.Store? I have looked over the page dcc.Upload | Dash for Python Documentation | Plotly , dcc.Store | Dash for Python Documentation | Plotly as well as other forums but cannot find a good way to connect the two.
If there is a simple fix or some way of doing it please feel free to post or comment!
Thanks
Could you explain a little more about your goal.
I use to get the CSV file in Pandas with read_csv(), not sure if this is useful for your needs
Hello sorry for the delay.
So I am using the upload button to input a csv which I then would like to affect a dropdown/checklist.
I see on the dcc.Upload page where one could use the csv to make a table but I am trying to have the values read into a store and then update a dropdown/checklist.
Would something like that be possible? I feel I am close:
def update_interactives(contents, filename, mcn, store):
if contents:
# contents = contents[0]
# filename = filename[0]
df = parse_contents(contents, filename)
for x in range(len(df)):
df[‘Values’] = df[‘Values’].strip(’][’).split(’, ')
df[‘Values’] = [i.strip("’") for i in df[‘Values’]]
upload=dict(zip(df[‘MCN’],df[‘Values’]))
store[mcn]= upload[mcn]
return(store[mcn])
Hello!
This is probably already answered somewhere, but I want to make use of dcc.store so that I can use my uploaded data for displaying dropdown options dynamically instead of loading data from the local system. however, I cannot make it work the way i want it to. Any help would be appreciated, thank you!
here is a simplified version of my code:
#uploading
upload_layout = html.Div([
dbc.Row([
dbc.Col([
html.Label("Upload your data"),
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '80%',
'height': '300px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px',
'align-items': 'center',
'justify-content': 'center'
},
# Allow multiple files to be uploaded
multiple=True
),
# data set view
html.Div(id='output-data-upload'),
html.Div(id='output-data-size'),
],align='center')
]),
#navigation buttons/links
dbc.Row([dbc.Col([dbc.Button("Proceed",color='danger',id='user-given-data-inputs')],align='center')]),
data_info(),
],style={'background-color':'black',
'color': 'white',
'align-items': 'center',
'justify-content': 'center',
})
#modal layout(where I want my dropdowns to show)
def data_info():
return html.Div([
dbc.Modal(
[
dbc.ModalHeader(dbc.ModalTitle("Further Information")),
dbc.ModalBody([
dbc.Row([
html.Label("Select Target Variable"),
dbc.Col([dcc.Dropdown(id='target-variable-dropdown')],align='center',width={'size':6,'offset':3}),
html.Br(),
html.Br(),
html.Label("select categorical variables"),
dbc.Col([dcc.Dropdown(multi=True)],align='center',width={'size':6,'offset':3}),
html.Br(),
html.Br(),
dbc.Row([
html.Label("Specify train-test-split size"),
dbc.Col([dcc.Dropdown(placeholder='Testing Data split(in %)'),
html.Br()],align='center',width={'size':6,'offset':3,'order':2})
])
],
)
]),
dbc.ModalFooter(dcc.Link(dbc.Button("Submit",color='danger',id='info-submit'),href='/data-summary'))
],id='data-info-modal',
scrollable=True,
is_open=False
)
])
#functions
def parse_contents(contents, filename, date):
logging.info("parsing contents of uploaded file")
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')))
df.to_csv(os.path.join(path_config.DATA_DIR,"raw",filename),sep=',')
elif 'xls' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
df.to_excel(os.path.join(path_config.DATA_DIR,"raw",filename))
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
#returning an html div
return html.Div([
dcc.Store(id='stored-data',storage_type="session"),
html.H5(filename),
html.H6(datetime.datetime.fromtimestamp(date)),
dash_table.DataTable(
df.to_dict('records'),
[{'name': i, 'id': i} for i in df.columns],
style_table={
'overflowY': 'scroll',
'maxHeight': '500px',
'color':'grey',
},
style_cell={'padding': '5px',
'backgroundColor': 'black',
'fontWeight': 'bold'},
style_header={
'backgroundColor': 'black',
'fontWeight': 'bold'
}
),
html.Br(),
html.Div(["Number of rows: " + str(df.shape[0]) + " ,Number of columns: " + str(df.shape[1])]),
html.Label("file uploaded"),
html.Br(),
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'
# })
])
#callbacks
# file upload callback
@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):
logging.info("upload contents")
if list_of_contents is not None:
children = [
f_util.parse_contents(c, n, d) for c, n, d in
zip(list_of_contents, list_of_names, list_of_dates)]
return children
##storing uploaded data in dcc.store for other callbacks to use
@app.callback(Output('stored-data','data'),
[Input('upload-data', 'contents'),
],
)
def store_data(contents):
if contents is None:
raise PreventUpdate
else:
df = pd.DataFrame(contents)
print("what is getting stored",df.shape)
return df.to_dict("records")
#the form layout
@app.callback(Output('data-info-modal','is_open'),
[Input('user-given-data-inputs','n_clicks'),Input('info-submit','n_clicks')],
State('data-info-modal','is_open'))
def input_info(n1,n2,is_open):
if n1 or n2:
return not is_open
return is_open
#dropdown options
@app.callback(Output('target-variable-dropdown','options'),Input('stored-data','data'))
def output_column_options(data):
if data is None:
raise PreventUpdate
else:
data = pd.DataFrame(data)
print(data.shape)
options = [{'label':i,'value':i} for i in data.columns]
return options