Related
This is a strange error, and one that has been asked before here but unfortunately went unanswered.
I have taken the code from the Dash official documentation here, which allows the user to upload a csv or xls file and view it as a datatable in the dash web app. I've copied and pasted the code below:
import base64
import datetime
import io
import dash
from dash.dependencies import Input, Output, State
from dash import dcc, html, dash_table
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
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'),
])
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 html.Div([
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]
),
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
if __name__ == '__main__':
app.run_server(debug=True)
The above code works flawlessly, as one would expect from code taken from the official documentation. Below is my code, which works perfectly except for the feature taken from the above documentation. I didn't change the code at all.
import pandas as pd
import numpy as np
import plotly.express as px
import dash
from dash import html, Dash, dcc, dash_table
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import dash_split_pane
import base64
import io
import datetime
from pandas.tseries.offsets import BDay
import plotly.graph_objects as go
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = Dash(__name__, external_stylesheets=external_stylesheets)
columnNames = ["Blood Lactate", "Velocity (km/h)", "Stage Finish Time (MM:SS)"]
df = pd.DataFrame(columns=columnNames)
df.rename_axis("Stage", inplace=True, axis=0)
columnIds = ["bloodLactate", "velocity", "stageFinishTime"]
# ------------------------------------------------------------------------
input_types = ['number', 'number', 'text']
row1 = html.Div(
[
dbc.Row([
dbc.Col([
html.Div([
html.P("Blood Lactate:", style={"margin-left":20}),
dcc.Input(
id="bloodLactateId",
type="number",
placeholder="insert Blood Lactate",
minLength=0, maxLength=50,
autoComplete='on',
disabled=False,
readOnly=False,
required=False,
size=20,
style={"margin-right":20}
)
], style=
{
"display":"flex",
"justify-content":"space-between",
"align-items":"baseline",
"margin-top":20
}
)
])
])
]
)
row2 = html.Div(
[
dbc.Row([
dbc.Col([
html.Div([
html.P("Velocity (km/h):", style={"margin-left":20}),
dcc.Input(
id="velocityId",
type="number",
placeholder="insert Velocity",
minLength=0, maxLength=50,
autoComplete='on',
disabled=False,
readOnly=False,
required=False,
size="20",
style={"margin-right":20}
)
], style={
"display":"flex",
"justify-content":"space-between",
"align-items":"baseline"})
]),
])
]
)
row3 = html.Div(
[
dbc.Row([
dbc.Col([
html.Div([
html.P("Stage Finish Time (MM:SS):",
style={"margin-left":20}),
dcc.Input(
id="stageFinishTimeId",
type="text",
placeholder="insert (MM:SS)",
minLength=0, maxLength=50,
autoComplete='on',
disabled=False,
readOnly=False,
required=False,
size="20",
style={"margin-right":20}
)
], style={"display":"flex",
"justify-content":"space-between",
"align-items":"baseline"})
]),
])
]
)
row4 = html.Div(
dbc.Row(
html.Button('Add Row',
id='add_row',n_clicks=0),
style={"text-align":"center"}
)
)
row5 = html.Div([
dcc.Upload(
id="upload-data", children=html.Div([
'Drag and Drop COSMED file or ', html.A('Select Files')
] ),
style={
'width':'80%',
"lineHeight":"60px",
'borderWidth':'1px',
'borderStyle':'dashed',
'borderRadius':'5px',
'text-align':'center',
'margin-left':'auto',
'margin-right':'auto',
'margin-top':40,
}
)
], style={"align-content":'center'})
table = html.Div([
dbc.Row([
dbc.Col([html.H5('Results',
className='text-center',
style={"margin-left":20}),
dash_table.DataTable(
id='table-container_3',
data=[],
columns=[{"name":i_3,"id":i_3,'type':'numeric'} for i_3 in df.columns],
style_table={'overflow':'scroll','height':600},
style_cell={'textAlign':'center'},
row_deletable=True,
editable=True),
],width={'size':12,"offset":0,'order':1})
]), html.Div(id='output-data-upload')
])
pane1 = html.Div([
row1,
html.Br(),
row2,
html.Br(),
row3,
html.Br(),
row4,
html.Br(),
row5
])
pane2 = html.Div(
table
)
app.layout = dash_split_pane.DashSplitPane(
children=[pane1, pane2],
id="splitter",
split="vertical",
size=500
)
#copy pasted code from docs ======================================================
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 html.Div([
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]
),
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('table-container_3', 'data'),
Output('bloodLactateId', 'value'),
Output('velocityId', 'value'),
Output('stageFinishTimeId', 'value'),
Input('add_row', 'n_clicks'),
State('table-container_3', 'data'),
State('table-container_3', 'columns'),
State('bloodLactateId', 'value'),
State('velocityId', 'value'),
State('stageFinishTimeId', 'value'))
def add_row(n_clicks, rows, columns, selectedBloodLactate, selectedVelocity,
selectedStageFinishTime):
if n_clicks > 0:
rows.append({c['id']: r for c,r in zip(columns,
[selectedBloodLactate,
selectedVelocity,
selectedStageFinishTime])})
return rows, '', '', ''
#copy pasted code ===============================================================
#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
#=================================================================================
if __name__ == '__main__':
app.run_server(debug=False)
Here is a photo of what the app looks like, to get an idea.
When I load the app it runs as expected, I can add rows, but when I upload a csv file I get the following error:
File "C:\Users\harry\OneDrive\Documents\coding\fypWebApp\dashApp\app.py", line 255, in update_output
zip(list_of_contents, list_of_names, list_of_dates)]
TypeError: 'float' object is not iterable
It seems the problem lies in one of the lists in the update_output function. Also, I get the following notice in VSCode.
This notice does not appear when I have just the code taken from the documentation in a standalone file (as seen in the image below), only when I enter the code into my code.
I don't know where to start to fix this problem, and it seems like it requires a good understanding of Dash to solve. Any help is appreciated.
After long debugging, the problem is that list_of_dates is a float number which represents the last modified for the uploaded file. There is a list comprehension in the callback which iterates through this float number, which does not make sense to iterate through a number, and it eventually throws an error. To solve this problem, all you should do is to replace the callback function with the following:
def update_output(list_of_contents, list_of_names, list_of_dates):
if list_of_contents is not None:
children = [parse_contents(list_of_contents, list_of_names, list_of_dates)]
return children
Inside the function parse_contents, I added the delimiter=";" to read the CSV file properly.
if 'csv' in filename:
# Assume that the user uploaded a CSV file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')), delimiter=";") #<-- this line.
Finally, I reduced the size of the upper table to show the table of the CSV file.
Output
I am working on a selection menu where the user can select the number of experiments they want to compare/see. Depending on this number I would like to adapt the number of columns that appear, being one for each experiment. In the image below an example of the menu with one experiment can be seen. However, I would like these dropdowns to duplicate if the user selects two experiments having them in side-to-side columns.
Here is an example of one column and one experiment:
The code I have so far is the following:
# Load Data
df = px.data.tips()
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
# Build App
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
# first row - selecting the number of experiments
html.Div([
html.I("Select the number of experiments you want to compare (min - 2 and max - 10):"),
html.Br(),
# input box for the number of experiments
dcc.Input(id="num_exp" , type='number', min = 2, max = 10, placeholder="No of experiments"),
html.Div(id="output")
], style = {'width': '100%'}
),
# second row - where the experiments are organized in columns
html.Div([
html.Label([
html.I("X axis "),
dcc.Dropdown(
id = 'dd_axis',
clearable = False,
placeholder = 'Select property x-axis',
options=[
{'label': i, 'value': i}
for i in properties
],
style={
'width': '100%'
})
]),
html.Label([
html.I("Y Axis "),
dcc.Dropdown(
id = 'dd_yaxis',
clearable = False,
placeholder = 'Select property y-axis',
options=[ ],
disabled = False)
])
], style = {'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '3vw', 'margin-top': '3vw', 'width': '50%'})
])
#app.callback(
Output("output", "children"),
# number of experiments input
Input("num_exp", "value"),
)
def update_output(test_type):
in_testtype = test_type
return u'{} experiments'.format(test_type)
def cb_render(*vals):
return " | ".join((str(val) for val in vals if val))
Can you help me adding more dropdown menus to the side and dividing the second row in columns based in the user selection?
Thank you!
You can do this by using dbc.Col and dbc.Row.
In your layout, have a Div and within it an empty dbc.Row that will be used to populate its children attribute with columns.
Then, in the callback that is triggered by the input box value, have a loop that returns the number of columns you want, with the relevant code for the dbc.Col and what you'd like to display in it.
Here's a worked-up example of your original code:
import dash
from dash import dcc, html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
properties = ["a", "b", "c"]
app.layout = html.Div([
# first row - selecting the number of experiments
html.Div([
html.I(
"Select the number of experiments you want to compare (min - 2 and max - 10):"),
html.Br(),
# input box for the number of experiments
dcc.Input(id="num_exp", value=2, type='number', min=2,
max=10, placeholder="No of experiments"),
html.Div([
dbc.Row([], id="output")
])
], style={'width': '100%'}
),
])
#app.callback(
Output("output", "children"),
# number of experiments input
Input("num_exp", "value"),
)
def update_output(test_type):
columns_list = []
letters = "xyzabcdefg"
for i in range(test_type):
columns_list.append(
dbc.Col([
html.Label([
html.I(f"{letters[i].upper()} axis "),
dcc.Dropdown(
id=f'{letters[i]}_axis',
clearable=False,
placeholder=f'Select property {letters[i]}-axis',
options=[
{'label': i, 'value': i}
for i in properties
],
style={
'width': '100%'
})
])
])
)
return columns_list
if __name__ == "__main__":
app.run_server(debug=True)
I'm new to Dash and Python. I have an app with a dropdown and a search input however I cannot get the callback to get both inputs to work. Currently either only the dropdown will work or just the input. I would like to first select the dropdown and then be able to search for text within the Datatable.
Below is my code.
import pandas as pd
import dash
import dash_table
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
import pathlib
from dash.dependencies import Input, Output
df = pd.read_csv('data.csv',encoding='cp1252')
env_list = df["Environment"].unique()
PAGE_SIZE = 20
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]
)
def description_card():
"""
:return: A Div containing logo.
"""
return html.Div(
id="description-card",
children=[
html.Img(id="logo", src=app.get_asset_url("logo.png"), height=80)
],style={'textAlign': 'center'}
)
def generate_control_card():
"""
:return: Descriptions
"""
return html.Div(
id="env-card",
children=[
html.H3("Welcome to the Package Catalog"),
]
)
app.layout = html.Div(
id="app-container",
children=[
# Banner
html.Div(
id="banner",
className="banner",
children=[description_card(),generate_control_card()
],
),
html.Div([
html.P([
html.Label("Select Environment", style={"background": "#F5F5F5"}),
dcc.Dropdown(
id='env-select',
options=[{'label': i, 'value': i} for i in env_list],
value=env_list[0],
)]),
html.Div([
html.P([
html.Label("Search for a package and description in the search box.", style={'display':'inline-block', 'background': '#F5F5F5'}),
dcc.Input(value='', id='filter-input', placeholder='Filter', debounce=True)
]),
dash_table.DataTable(css=[{'selector': '.row', 'rule': 'margin: 0'}],
id='datatable-paging',
columns=[
{"name": i, "id": i} for i in df.columns # sorted(df.columns)
],
style_header={
'backgroundColor': 'F5F5F5',
'fontWeight': 'bold'
},
page_current=0,
page_size=PAGE_SIZE,
page_action='custom',
sort_action='custom',
sort_mode='single',
sort_by=[]
)
]),
]),
])
#app.callback(
Output('datatable-paging', 'data'),
[
Input('datatable-paging', 'page_current'),
Input('datatable-paging', 'page_size'),
Input('datatable-paging', 'sort_by'),
Input('env-select', 'value'),
Input('filter-input', 'value')
])
def update_table(page_current, page_size, sort_by, environment_input, filter_string,
):
# Filter
dff = df[df.Environment==environment_input]
dff = df[df.apply(lambda row: row.str.contains(filter_string, regex=False).any(), axis=1)]
# Sort
if len(sort_by):
dff = dff.sort_values(
sort_by[0]['column_id'],
ascending=sort_by[0]['direction'] == 'asc',
inplace=False
)
return dff.iloc[
page_current * page_size:(page_current + 1) * page_size
].to_dict('records')
Change this line
dff = df[df.apply(lambda row: row.str.contains(filter_string, regex=False).any(), axis=1)]
to this
dff = dff[df.apply(lambda row: row.str.contains(filter_string, regex=False).any(), axis=1)]
In the line before the one shown above you apply your dropdown filter and store the filtered result as dff. So by using df instead of dff you're essentially discarding the dropdown filter result.
I am trying to set up a dash app which has 2 layers:
1st page has a couple of input forms, and based on these inputs - app_layout
2nd page - which has a different set of intputs (layout_more_inputs) which pop up depending on what 1st page input is.
I am trying to return layout_more_inputs from a callback but it doesn't work.
app.layout = html.Div([
html.H3('welcome to app'),html.Br(),
dcc.Input(id='input-00-state', type='text', value='QQQ'),
dcc.Input(id='input-01-state', type='text', value='MOVE'),
html.Button(id='submit-button-state', n_clicks=0, children='Go!'),
html.Div(id='output-state'),
dcc.Graph(id='graph-with-slider'),
])
layout_more_inputs = html.Div([
dcc.Input(id='input-10-state', type='number', value='0.11'),
dcc.Input(id='input-11-state', type='number', value=0.12),
html.Button(id='submit-button-state2', n_clicks=0, children='Go Go!'),
])
#front page - 0
#app.callback(
Output('container', 'children'),
Input('submit-button-state', 'n_clicks'),
State('input-00-state', 'value'),
State('input-01-state', 'value'),
)
def ask_for_more_inputs(n_clicks,asset_str,event_str):
print("input summary:")
print(n_clicks,asset_str,event_str)
return layout_more_inputs #<<--DOES NOT WORK
#front page - 1
#app.callback(
Output('graph-with-slider', 'figure'),
Output('output-state', 'children'),
Input('submit-button-state2', 'n_clicks'),
State('input-10-state', 'value'),
State('input-11-state', 'value'),
)
def more_inputs(n_clicks,input0,input1):
d = {'x': [input0, input1], 'y': [input0, input1]}
df = pd.DataFrame(data=d)
filtered_df = df
fig = px.scatter(filtered_df, x="x", y="y")
fig.update_layout(transition_duration=500)
return fig, u'''Button pressed {} times, 1 is "{}", and 2 is "{}"'''.format(n_clicks,state1,state2)
if __name__ == '__main__':
app.run_server(debug=True)
I'm not 100% on what exactly is is you're attempting to deliver, but one options would be to use Dash's dcc.Tabs property.
I've started & laid the groundwork, sort of, for you:
import sys
import dash
from dash import html
from dash import dcc
from dash import no_update
from dash.dependencies import Input, Output, State
# app = dash.Dash(__name__)
app = JupyterDash()
layout = html.Div([
html.H3('welcome to app'),
html.Br(),
dcc.Input(id='input-00-state', type='text', value='QQQ'),
dcc.Input(id='input-01-state', type='text', value='MOVE'),
html.Button(id='submit-button-state', n_clicks=0, children='Go!'),
html.Div(id='output-state'),
dcc.Graph(id='graph-with-slider'),
])
layout_more_inputs = html.Div([
dcc.Input(id='input-10-state', type='number', value=0.11),
dcc.Input(id='input-11-state', type='number', value=0.12),
html.Button(id='submit-button-state2', n_clicks=0, children='Go Go!'),
])
tabs = [
dcc.Tab(label="Front Page - 0", children=layout),
dcc.Tab(label="Front Page - 1", children=layout_more_inputs)
]
multitab_layout = [dcc.Tabs(id="tabs", children=tabs)]
app.layout = html.Div(
[html.Div(id="multitab_layout", children=multitab_layout)])
# front page - 0
#app.callback(
Output('container', 'children'),
Input('submit-button-state', 'n_clicks'),
[State('input-00-state', 'value'),
State('input-01-state', 'value')]
)
def ask_for_more_inputs(n_clicks, asset_str, event_str):
print("input summary:")
print(n_clicks, asset_str, event_str)
return layout_more_inputs # <<--DOES NOT WORK
# front page - 1
#app.callback([
Output('graph-with-slider', 'figure'),
Output('output-state', 'children')
], Input('submit-button-state', 'n_clicks'),
Input('submit-button-state2', 'n_clicks'), [
State('input-00-state', 'value'),
State('input-01-state', 'value'),
State('input-10-state', 'value'),
State('input-11-state', 'value')
])
def more_inputs(n_clicks, n_cliks2, input0, input1, state0, state1, state10,
state11):
d = {'x': [input0, input1], 'y': [input0, input1]}
df = pd.DataFrame(data=d)
filtered_df = df
fig = px.scatter(filtered_df, x="x", y="y")
fig.update_layout(transition_duration=500)
return fig, u'''Button pressed {} times, 1 is "{}", and 2 is "{}"'''.format(
n_clicks, state1, state2)
if __name__ == '__main__':
app.run_server(debug=True)
using your provided code; but not entirely sure where exactly you'd want it to go from here. In terms of UI/EX behavior etc. Perhaps this may be enough of a clue to get you going as you need to...
I would like to launch my Dash with my dropdown hide and after selecting something on another dropdown unhide my first dropdown. Idk if you have any idea, maybe it's a mistake on my little script.
This is a little example :
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash('example')
app.layout = html.Div([
dcc.Dropdown(
id = 'dropdown-to-show_or_hide-element',
options=[
{'label': 'Show element', 'value': 'on'},
{'label': 'Hide element', 'value': 'off'}
],
value = 'off'
),
# Create Div to place a conditionally visible element inside
html.Div([
# Create element to hide/show, in this case an 'Input Component'
dcc.Input(
id = 'element-to-hide',
placeholder = 'something',
value = 'Can you see me?',
)
], style= {'display': 'none'} # <-- This is the line that will be changed by the dropdown callback
)
])
#app.callback(
Output(component_id='element-to-hide', component_property='style'),
[Input(component_id='dropdown-to-show_or_hide-element', component_property='value')])
def show_hide_element(visibility_state):
if visibility_state == 'on':
return {'display': 'block'}
if visibility_state == 'off':
return {'display': 'none'}
if __name__ == '__main__':
app.server.run(debug=False, threaded=True)
By slightly changing your code (I changed the parameter that your function takes and using that same parameter in the if statement, this code seems to work). I also change the original style to block, which allows the element to be there, but only shown when on the show dropdown.
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash('example')
app.layout = html.Div([
dcc.Dropdown(
id = 'dropdown-to-show_or_hide-element',
options=[
{'label': 'Show element', 'value': 'on'},
{'label': 'Hide element', 'value': 'off'}
],
value = 'off'
),
# Create Div to place a conditionally visible element inside
html.Div([
# Create element to hide/show, in this case an 'Input Component'
dcc.Input(
id = 'element-to-hide',
placeholder = 'something',
value = 'Can you see me?',
)
], style= {'display': 'block'} # <-- This is the line that will be changed by the dropdown callback
)
])
#app.callback(
Output(component_id='element-to-hide', component_property='style'),
[Input(component_id='dropdown-to-show_or_hide-element', component_property='value')])
def show_hide_element(value):
if value == 'on':
return {'display': 'block'}
if value == 'off':
return {'display': 'none'}
if __name__ == '__main__':
app.server.run(debug=False)