python - Dash - 上传 CSV 并呈现图表
问题描述
我是 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)
解决方案
推荐阅读
- ms-access - VBA Do While 循环
- javascript - TypeScript 错误“找不到模块的声明文件” - 无法修复
- node.js - Mongoose:作为响应返回存储的日期字段作为时间戳(自 Unix 纪元以来的毫秒数)
- node.js - NodeJS将base64附加到文件
- django - 在 django 中设置多个 MEDIA_URL 和 MEDIA_ROOT
- javascript - Promises 的问题并在 Javascript 中抛出新的错误
- postgresql - 嵌套 jsonb 字段上的慢速不同 PostgreSQL 查询不会使用索引
- sorting - SAS:提取按日期排序的最后一个唯一组合
- python-3.x - 按钮/标签未显示在新窗口上(Python tkinter)
- apache-spark - Spark sortMergeJoin 连续运行