Loading pandas dataframe into Data table through a callback


#1

So, I have been excited by the continued improvement of Data Tables, but despite looking through many threads around here as well as guides, I can’t figure out the proper way to simply import a pandas dataframe into a data table.

Most examples illustrate how to manually pick certain columns/rows taken from a dataframe that is hardcoded within the example, and display that, but I have a dataframe that needs to be created via a callback, which will then be sent to 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, but nothing displays.

## 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
from twitter_functions import id_extractor, old_tweets, continuous_stream

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)

How can I do this?


#2

If I’m not mistaken, you may have to define the DataTable with the columns you want and an empty list for data i.e.:

dash_table.DataTable(
    id='computed-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'},
    ...
                ],
    data=[],
    ...

where obviously the structure of you DataTable in declaration matches the df you are trying to display


#3

This ended up working. Thank you so much, sterlingbutters; you saved a fellow coder in a great time of need.

Plotly really needs to do a better job of documenting these bedrock-basic features. I think I’ll make a forum post at some point documenting all the little tricks I’ve learned over the last couple months, in the hopes possibly they’ll help others like me in the future.


#4

yup, only way i figured it out was because I had two DataTables that were exactly the same except that was the only difference haha so I guess you could say I got lucky