user-interface - 在 Dash 的其他组件中使用来自上传的数据的问题
问题描述
在用 Dash 编写程序时,我遇到了一些问题。使用 Upload 组件时,我很难在其他组件上正确使用该数据。我的目标是使用上传的数据(CSV 文件)来向 2 个相同的下拉组件添加选项,这些组件是导入文件的列的名称。之后将使用下拉列表中的选定值作为图表的轴来生成图表。
任何帮助,将不胜感激。
import base64
import datetime
import io
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.express as px
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
df = pd.DataFrame()
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Div(children='this is an attempt to do stuff right'),
dcc.Dropdown(id='Drop1'),
dcc.Dropdown(id='Drop2'),
dcc.Dropdown(id='graphtype', options=[
{'label': 'Bar', 'value': 'Bar'},
{'label': 'Scatter', 'value': 'Scatter'},
{'label': 'Histogram', 'value': 'Hist'}
]),
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'),
dcc.Graph(id='output-graph')
]
)
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(
data=df.to_dict('records'),
columns=[{'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)]
print(children)
return children
if __name__ == '__main__':
app.run_server(debug=True)
解决方案
这是文档中的页面,应该为您提供所需的一切。如果您上传 CSV 文件,您可以使用:
df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
并从那里将其用作普通的熊猫数据框。
推荐阅读
- javascript - 如何为属于夏令时的未来日期更正时区偏移
- draw - libreoffice Basic:绘图和表格形状:如何格式化单元格?
- javascript - 将 websocket ref 传递给子组件
- c++ - Google Kickstart 2020 Round A 2020 错误答案
- ios - UIvew 在不同位置使用相同的代码
- flutter - 访问 Cloud Firestore 会引发 NoSuchMethodError
- excel - VBA - 使用范围函数从一个工作表复制并粘贴到另一个工作表
- python - 是否可以从其他人的不和谐服务器中获取消息?
- laravel - Laravel eloquent 得到一个二维数组的数组
- server-side-rendering - 使用 Svelte 进行动态服务器端渲染。如何在客户身上补水?