【发布时间】:2019-06-09 20:06:30
【问题描述】:
我正在尝试创建一个绘图界面,用户可以在其中上传不带标题的 csv 文件并上传包含标题的单独文本文件。 The csv file will be shown in a table, and when the text file is selected and loaded, the column headers of the datatable will be replaced with the column headers contained within the text file.
我尝试了两种方法来做到这一点: 第一个是在 app.layout 中有一个 div,并让一个回调函数将一个数据表返回到该 div。使用此方法,数据表加载正确,但我不知道如何引用和更改此表的列。
第二种方法是在app.layout中有一个空白表,并有一个回调函数使用pandas to_dict()返回数据。使用这种方法,我可以通过 id 引用表并更改其列。但是,当我运行回调函数时,生成的数据表是空白的(尽管行数似乎是正确的)。
这是 app.layout
app.layout = html.Div([
html.H1('Upload File'),
dcc.Upload(
id ='upload_data',
children = html.Button('Select Data File',
id = 'load_data_button')
),
html.H2('Upload Headers'),
dcc.Upload(
id ='upload_headers',
children = html.Button('Select Headers File',
id = 'load_header_button')
),
html.Div(id = 'my_headers'),
html.Div(id = 'my_data'),
html.Div(
dash_table.DataTable(
id = 'load_data_table'
)
)
])
虽然这是有问题的回调
@app.callback(
Output('load_data_table', 'data'),
[Input('upload_data', 'contents')]
)
def update_table(content):
if content is not None:
content_type, content_string = content.split(',')
decoded = base64.b64decode(content_string)
df = pd.read_csv(io.BytesIO(decoded), header = None)
return df.to_dict('records')
else:
return [{}]
这是我提到的第二种方法的代码。如图所示,初始表数据没有设置,输出映射到表的数据。
我预计数据会出现在表格中,但实际发生的是表格单元格是空白的。但是,行数是正确的(即,如果我的 csv 是 5 行,它会生成 5 行空单元格),这让我认为至少通过回调发送了一些东西。
有人知道如何修复我提到的两种方法或知道更好的方法来完成这项任务吗?
【问题讨论】: