我是Dash的新手,并试图学习如何做一个看似微不足道的功能:上传CSV并将其用作数据框。大多数示例显示引用本地csv文件。我不确定下一步是让Dash引用我以CSV格式上传的数据。到目前为止,我编写的代码允许用户上载CSV文件并呈现表格。接下来的事情应该是从CSV文件中选择特定的列并生成一个简单的折线图。任何建议表示赞赏!
import dash_html_components as html
import dash_core_components as dcc
import dash
import plotly
import dash_table_experiments as dte
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
import json
import datetime
import operator
import os
import base64
import io
app = dash.Dash()
app.scripts.config.serve_locally = True
app.config['suppress_callback_exceptions'] = True
app.layout = html.Div([
html.H5("Upload Files"),
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'
},
multiple=False),
html.Br(),
html.H5('filename'),
html.Div(dte.DataTable(rows=[{}], id='table'))
])
# Functions
# file upload function
def parse_contents(contents, filename):
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 None
return df
# callback table creation
@app.callback(Output('table', 'rows'),
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')])
def update_output(contents, filename):
if contents is not None:
df = parse_contents(contents, filename)
if df is not None:
return df.to_dict('records')
else:
return [{}]
else:
return [{}]
# callback Graph Creation - not sure how to reference the csv file that was
uploaded. Just want to create a simple line graph or scatter plot with two
of the variables in the file
app.css.append_css({
"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"
})
if __name__ == '__main__':
app.run_server(debug=True)