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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54622557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:19:10  来源:igfitidea点击:

Python Dash: loading pandas dataframes into data table

pythonpandasplotly-dash

提问by Coolio2654

I have been trying to build an app with Dashrecently, but despite looking through the many guides, I simply cannot figure out how to import a pandas dataframe into Dash's data table (which is essentially a pandas dataframe, except web-hosted and reactive).

我最近一直在尝试使用Dash构建一个应用程序,但是尽管浏览了许多指南,我还是无法弄清楚如何将 Pandas 数据框导入 Dash 的数据表(它本质上是一个 Pandas 数据框,除了网络托管和反应式) .

Most examples illustrate how to manually pick certain columns/rows taken from a dataframe which is already hardcoded within the example, like in here. However, in, my situation, the dataframe is built within my code (and pandas is the easiest way to do this), so I end up having to figure out a way to convert a pd.Dataframe()into a dash_table.DataTable().

大多数示例说明了如何从示例中已经硬编码的数据帧中手动选择某些列/行,例如此处。但是,在我的情况下,数据框是在我的代码中构建的(而 Pandas 是最简单的方法),所以我最终不得不想办法将 apd.Dataframe()转换为dash_table.DataTable().

How can I make this work? Using the references, I've tried the following code to send a dict of my dataframe to dash_table.DataTable(), but nothing displays.

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

My code:

我的代码:

## 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)

采纳答案by Coolio2654

After someonealso replied to me on the plotly forums (thankfully), it seems the final answer is to pre-set one's Data Table with the columns of the pandas dataframe that is going to go into it at some point, like this,

有人还在 plotly 论坛上回复了我(谢天谢地)之后,似乎最终的答案是预先设置一个数据表,其中包含将在某个时候进入的 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'}]
)

, and then send in a dict of your pandas dataframe.

,然后发送您的Pandas数据帧的字典。

回答by haydard

Assuming your tweets function returns a dataframe, adding table columns as a second output to your callback should work.

假设您的 tweets 函数返回一个数据帧,将表列作为第二个输出添加到您的回调应该可以工作。

@app.callback(
    [Output(component_id='tweet_table', component_property='data'),
     Output(component_id='tweet_table', component_property='columns')
    [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)
    columns = [{'name': col, 'id': col} for col in tweets.columns]
    data = tweets.to_dict(orient='records')
    return data, columns

回答by Jamie

Here is another solution that worked for me:

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

     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')
        )

My biggest problem was that my app kept throwing an exception on whatever I was trying to pass into the 'columns' argument for dash_table.DataTable(...).

我最大的问题是我的应用程序不断抛出异常,无论我试图传递给 dash_table.DataTable(...) 的“列”参数。

Hopefully this will help with not having to hard-code anything.

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

回答by Peter Leimbigler

This is a bit of a long shot and untested, but based on https://community.plot.ly/t/dash-datatable-using-callbacks/6756, it seems Dash DataTables implicitly require an initial value if you're going to modify them via callback.

这有点远并且未经测试,但基于https://community.plot.ly/t/dash-datatable-using-callbacks/6756,如果你要去的话,Dash DataTables 似乎隐含地需要一个初始值通过回调修改它们。

Try changing this line:

尝试更改此行:

dash_table.DataTable(id='tweet_table')

To this:

对此:

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