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

2024-02-11

我一直在尝试构建一个应用程序Dash https://plot.ly/products/dash/最近,尽管浏览了许多指南,我还是无法弄清楚如何将 pandas 数据框导入到 Dash 的数据表中(本质上是一个 pandas 数据框,除了网络托管和反应式之外)。

大多数示例说明了如何手动选择从示例中已硬编码的数据帧中获取的某些列/行,例如here https://dash.plot.ly/datatable。然而,在我的情况下,数据帧是在我的代码中构建的(pandas 是做到这一点的最简单方法),所以我最终不得不找出一种方法来转换pd.Dataframe() into a dash_table.DataTable().

我怎样才能做到这一点?使用参考资料,我尝试了以下代码将我的数据帧的字典发送到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)

After someone https://community.plot.ly/t/loading-pandas-dataframe-into-data-table-through-a-callback/19354也在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'}]
)

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python Dash:将 pandas 数据帧加载到数据表中 的相关文章

随机推荐