我试图通过查看uploads tutorial来用Dash创建一些简单的东西,但是要用图形化数据来创建一个表格。
有没有人对我在解析数据时遇到的错误有任何提示?
File "C:\Users\benb\Desktop\dash\hwsLineUpload.py", line 105, in update_graph
df = parse_contents(contents, filename)
File "C:\Users\benb\Desktop\dash\hwsLineUpload.py", line 52, in parse_contents
content_type, content_string = contents.split(',')
ValueError: not enough values to unpack (expected 2, got 1)
这是完整的脚本,我知道我在def parse_contents(contents, filename):
函数中有一些错误。任何提示都有帮助,这里没有太多的智慧。
import base64
import datetime
import io
import cufflinks as cf
import plotly.graph_objs as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
colors = {
"graphBackground": "#F5F5F5",
"background": "#ffffff",
"text": "#000000"
}
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'
},
# Not multiple files to be uploaded
multiple=False
),
dcc.Graph(id='myGraph')
])
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')))
if df.empty:
df = df.fillna(method = 'ffill').fillna(method = 'bfill')
if df.isnull().values.any():
df = df.fillna(method = 'ffill').fillna(method = 'bfill')
elif 'xls' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
if df.empty:
df = df.fillna(method = 'ffill').fillna(method = 'bfill')
if df.isnull().values.any():
df = df.fillna(method = 'ffill').fillna(method = 'bfill')
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
return df
@app.callback(Output('myGraph', 'figure'),
[
Input('upload-data', 'contents'),
Input('upload-data', 'filename')
])
def update_graph(contents, filename):
fig = {
'layout': go.Layout(
plot_bgcolor=colors["graphBackground"],
paper_bgcolor=colors["graphBackground"])
}
if contents:
contents = contents[0]
filename = filename[0]
df = parse_contents(contents, filename)
df = df.set_index(df.columns[0])
fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
我用this git repo中的一个csv文件boilerData.csv测试这个文件
2条答案
按热度按时间eivgtgni1#
Parse_contents使用一个分隔符,默认情况下,逗号在分割内容本身时,它不能被分配给2个变量,因为只有一个值可以分配。使用content_string = parse_contents(x,y)再试一次
xfb7svmp2#
也许你已经发现了问题所在,但以下是我的回答,供以后参考:
问题是,如果你在
dcc.Upload
中设置multiple=False
,它的contents
和filename
不是列表,而是单个元素。对方法
update_graph
进行以下更改应该可以工作: