python - 使用 Dash 上传和创建表格
问题描述
我是 Plotly Dash 的新手,我想上传一个 csv 文件并创建一个表格。我可以上传 csv 文件,但它是作为元组而不是作为 pandas DataFrame 上传的,所以我无法使用 TableData 查看它。
app.layout =html.Div([
dcc.Upload(
id='upload',
children=html.Button('Import un fichier'),
),
html.Div(id="output_data"),])
def parse_data(contents, filename):
content_type, content_string = contents.split(",")
decoded = base64.b64decode(content_string)
try:
if "csv" in filename: #csv file
df = pd.read_csv(io.StringIO(decoded.decode("utf-8")), delimiter=',', decimal=','),
print(type(df)),
elif "xls" in filename: #xls file
df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print(e)
return html.Div(["There was an error processing this file."])
print(df)
return df
@app.callback(
Output("output_data", "children"),
Input("upload", "contents"),
Input("upload", "filename"),
)
def update_table(contents, filename):
# table = html.Div()
if contents:
df=parse_data(contents,filename)
table = html.Div(
[
html.H4(filename),
dash_table.DataTable(
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict("records"),
),
html.Hr(),
html.Div("Raw Content"),
html.Pre(
contents[0:200] + "...",
style={"whiteSpace": "pre-wrap", "wordBreak": "break-all"},
),
]
)
return table
我有这个错误AttributeError: 'tuple' object has no attribute 'columns'
解决方案
这是问题所在:
if "csv" in filename: #csv file
df = pd.read_csv(io.StringIO(decoded.decode("utf-8")), delimiter=',', decimal=','),
print(type(df)),
您已在这些行的末尾添加了逗号!这使得值元组。只需删除这些逗号,如下所示:
if "csv" in filename: #csv file
df = pd.read_csv(io.StringIO(decoded.decode("utf-8")), delimiter=',', decimal=',')
print(type(df))
推荐阅读
- react-native - 在 react-native-router-flux 中定义的 Router 组件内创建导航抽屉
- c++ - 附加字符串产生多行字符串
- css - 为什么我的字体没有使用这个 CSS 声明在 IE11 中呈现?
- c# - 如何使用 FakeItEasy 模拟服务?
- visual-studio - 通过windows应用打包项目创建App Package复制dll失败
- javascript - 在 Node.js 中,是否可以异步运行中间件功能?
- r - 如何避免结果生成器中的循环
- xml - 在 Dart / Flutter 中解析嵌套的 XML
- tsql - 将数据插入默认约束列时可以使用默认关键字吗?
- r - Tibble 数据到 excel