Python Dash:将pandas数据帧加载到数据表中

问题描述 投票:0回答:2

我最近一直试图用Dash构建一个应用程序,但是尽管查看了许多指南,我根本无法弄清楚如何将pandas数据框导入Dash的数据表(这实际上是一个熊猫数据帧,除了web托管和反应) 。

大多数示例说明了如何手动选取从示例中已经硬编码的数据帧中获取的某些列/行,例如here。但是,在我的情况下,数据框是在我的代码中构建的(并且pandas是最简单的方法),所以我最终必须找到一种方法将pd.Dataframe()转换为dash_table.DataTable()

我怎样才能做到这一点?使用引用,我尝试了以下代码将我的数据帧的dict发送到dash_table.DataTable(),但没有显示任何内容。

我的代码:

## Imports
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table

from dash.dependencies import Input, Output, State

import datetime as dt
import pandas as pd
import numpy as np

## Custom functions that creates the pandas dataframe
from twitter_functions import old_tweets

app = dash.Dash(dev_tools_hot_reload=True)
app.scripts.config.serve_locally = True
app.config['suppress_callback_exceptions'] = True


app.layout = html.Div(children=[

    html.H3('Twitter App'),

    dcc.Input('ScreenName_Input', type='text'),

    html.Button(id='screenNames_submit_button', children='Submit'),

    dash_table.DataTable(id='tweet_table')

])

@app.callback(
    Output(component_id='tweet_table', component_property='data'),
    [Input(component_id='screenNames_submit_button', component_property='n_clicks_timestamp')],
    [State(component_id='ScreenName_Input', component_property='value')]
)
def display_tweets(submit_button, screen_names):
    tweets = old_tweets(screen_names)

    return tweets.to_dict(orient='records')

if __name__ == '__main__':
    app.run_server(debug=True)
python pandas plotly-dash
2个回答
3
投票

someone也在情节论坛(谢天谢地)回复我之后,似乎最终的答案是预先设置一个数据表,其中包含pandas数据帧的列,这些数据帧将在某些时候进入,如下所示,

dash_table.DataTable(
    id='table',
    columns=[
    {'name': 'Column 1', 'id': 'column1'},
    {'name': 'Column 2', 'id': 'column2'},
    {'name': 'Column 3', 'id': 'column3'},
    {'name': 'Column 4', 'id': 'column4'},
    {'name': 'Column 5', 'id': 'column5'}]
)

,然后发送你的熊猫数据帧的字典。


1
投票

这是一个长镜头并且未经测试,但基于https://community.plot.ly/t/dash-datatable-using-callbacks/6756,如果您要通过回调修改它们,似乎Dash DataTables隐式需要初始值。

尝试更改此行:

dash_table.DataTable(id='tweet_table')

对此:

dash_table.DataTable(id='tweet_table', rows=[{}])

0
投票

这是另一个对我有用的解决方案:

     dt_col_param = []

     for col in output_df.columns:
            dt_col_param.append({"name": str(col), "id": str(col)})

    dash_table.DataTable(
            columns=dt_col_param,
            data=output_df.to_dict('records')
        )

我最大的问题是我的应用程序不断向我试图传递到dash_table.DataTable(...)的'columns'参数中的任何内容抛出异常。

希望这将有助于不必硬编码任何东西。

© www.soinside.com 2019 - 2024. All rights reserved.