Coo*_*654 0 python pandas plotly-dash
我最近一直在尝试使用Dash构建应用程序,但是尽管浏览了许多指南,但我仍然无法弄清楚如何将熊猫数据框导入Dash的数据表(本质上是熊猫数据框,但Web托管和响应式除外) 。
大多数示例说明了如何从示例中已经进行硬编码的数据帧中手动选择某些列/行,如此处所示。但是,在我的情况下,数据帧是在代码内构建的(而pandas是实现此目的的最简单方法),因此我最终不得不找出一种将a转换pd.Dataframe()为a的方法dash_table.DataTable()。
我该如何进行这项工作?使用引用,我尝试了以下代码将我的数据帧的字典发送到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)
Run Code Online (Sandbox Code Playgroud)
小智 6
假设您的 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
Run Code Online (Sandbox Code Playgroud)
在某人也在密谋论坛上回答了我之后(很感激),看来最终的答案是用一个熊猫数据框的列预先设置一个人的数据表,像这样,
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'}]
)
Run Code Online (Sandbox Code Playgroud)
,然后发送您的熊猫数据框的字典。