【发布时间】:2019-11-04 10:45:35
【问题描述】:
我正在按照本指南和文档将 excel 文件上传到仪表板:https://dash.plot.ly/dash-core-components/upload
我想知道如何在 pandas 数据框中显示我的上传结果。我的代码概述如下。从本质上讲,我的表格是某些百分比的状态细分,我正在尝试将其上传到我的仪表板中。
import base64
import datetime
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%',
'height': '120px',
'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'),
])
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.'
])
def generate_table(df, max_rows=10):
return html.Table(
# Header
[html.Tr([html.Th(col) for col in df.columns])] +
# Body
[html.Tr([
html.Td(df.iloc[i][col]) for col in df.columns
]) for i in range(min(len(df), max_rows))]
)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(children =[
html.H4(children = 'test'),
dcc.Dropdown( id = 'dropdown', options = [
{'label' : i , 'value' : i} for i in df.state.unique()
], multi = True, placeholder = 'Filter by State'),
html.Div(id='table-container'),
])
def display_table(dropdown_value):
if dropdown_value is None:
return generate_table(df)
#x = df[df['state'] == str(dropdown_value)]
return html.Div([
html.H5(filename),
html.H6(datetime.datetime.fromtimestamp(date)),
generate_table(df[df['state'].isin(dropdown_value)])
#app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})
@app.callback(
dash.dependencies.Output('table-container', 'children'),
[dash.dependencies.Input('dropdown','value')])
if __name__ == '__main__':
app.run_server(debug=True)
【问题讨论】:
-
您的意思是如何显示 pandas 数据框,就像它在 jupyter 笔记本中的输出一样?这个问题对我来说有点不清楚,因为本教程已经依赖于将数据读入 pandas 数据帧并显示它们。
-
嗨@djakubosky,是的。我想显示熊猫数据框,就像它在 Jupyter Notebook 中的输出一样。本质上,我希望能够使用我的仪表板,选择并上传一个 excel 文件,并在 pandas 数据框中显示上传的 excel 文件,就像在 jupyter 笔记本中一样
-
所以它需要保留它在笔记本中呈现方式的“样式”。基于一些挖掘,这似乎是一件棘手的事情。原生不支持渲染“原始”HTML - 但您可以提取样式。我会发布一个可能的解决方案
标签: python pandas dashboard plotly-dash