I have been trying to build an app with Dash recently, 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).
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()
.
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.
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 also 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,
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.