【发布时间】:2019-11-22 08:46:38
【问题描述】:
我正在从dash_core_components.Upload 读取一个文本文件(主要是.csv)。打印我拍摄的文件没有问题。但是,当我进行一些计算并尝试打印时出现问题。
错误是:
dash.exceptions.InvalidCallbackReturnValue:
The callback for property `children`
of component `dataframe_output` returned a value
which is not JSON serializable.
In general, Dash properties can only be
dash components, strings, dictionaries, numbers, None,
or lists of those.
这是我做过和尝试过的:
# importing required libraries
import dash
import dash_table
import pandas as pd
import dash_core_components as dash_core
import dash_html_components as dash_html
from dash.dependencies import Input, Output
# starting app layout
app.layout = dash_html.Div([
# upload button to take csv files
dash_core.Upload(id='upload_data',
children=dash_html.Div(['Drag and Drop or ',
dash_html.A('Select Files')
]),
style={'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
multiple=False),
# a 'Div' to return table output to
dash_html.Div(id='dataframe_output'),
])
# callback to take and output the uploaded file
@app.callback(Output('dataframe_output', 'children'),
[Input('upload_data', 'contents'),
Input('upload_data', 'filename')])
def update_output(contents, filename):
if contents is not None:
# reading the file
input_data = pd.read_csv(filename)
# creating a dataframe that has info about "data types", "count of nulls", "count of unique values"
info_dataframe = pd.concat([pd.DataFrame(input_data.dtypes, columns=["data_types"]),
pd.DataFrame(input_data.isna().sum(), columns=["count of blanks"]),
pd.DataFrame(input_data.nunique(), columns=["count of unique values"])
],
axis=1, sort=True)
# adding index as a row
info_dataframe.reset_index(level=0, inplace=True)
# returning it to 'Div'
return dash_html.Div([
dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in info_dataframe .columns],
# columns=[{"name": i, "id": i} for i in input_data.columns], # this works fine
data=info_dataframe .to_dict("rows"),
# data=input_data.to_dict("rows"), # this works fine
style_cell={'width': '50px',
'height': '30px',
'textAlign': 'left'}
)
])
# running the app now
if __name__ == '__main__':
app.run_server(debug=True, port=8050)
(我也想在浏览器上显示后将其保存到文本文件中。我该怎么做)。
【问题讨论】:
-
首先,我立即想知道的是,为什么您首先要发送一个充满
DataTable()的Div到另一个Div(dataframe_output)。是不是显得有些多余?尝试仅将DataTable()发送到占位符Div。其次,由于前面只是我的直觉,目前通常填充DataTable()的方式是通过创建一个空的,其中预设了正确的列名/id,然后 向DataTable()的data属性发送一个以 dict() 形式表示的 pandas 数据帧 - 例如。df.to_dict(orient='rows'). -
顺便说一句,
... returned a value which is not JSON serializable的 Dash 错误确实像看起来一样简单 - 确保所有回调只将正常输出发送到需要它们的地方(我怀疑发送 @987654335 @ 是什么让 Dash 感到困惑)。最后,如果您想将数据帧保存在临时位置以进行存储,如 FBruzzesi 所示,他描述了用户必须在其应用程序中存储内存的旧方式,该方式仍然有效,但您应该查看创建的较新组件为了帮助做到这一点,community.plot.ly/t/announcing-the-storage-component/13758 .
标签: python pandas dataframe datatable plotly-dash