Return a Pandas DataFrame as a data_table from a callback with Plotly Dash for Python

2024/11/6 2:59:34

I would like to read a .csv file and return a groupby function as a callback to be displayed as a simple data table with "dash_table" library. @Lawliet's helpful answer shows how to do that with "dash_table_experiments" library. Here is where I’m stuck:

import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
from dash.dependencies import Input, Output, Statedf = pd.read_csv('https://gist.githubusercontent.com/chriddyp/''c78bf172206ce24f77d6363a2d754b59/raw/''c353e8ef842413cae56ae3920b8fd78468aa4cb2/''usa-agricultural-exports-2011.csv')app = dash.Dash()
application = app.serverapp.layout = html.Div([dash_table.DataTable(id = 'datatable',        ),html.Div([html.Button(id='submit-button',                children='Submit')]),    ])@app.callback(Output('datatable','data'),[Input('submit-button','n_clicks')],[State('submit-button','n_clicks')])def update_datatable(n_clicks,csv_file):            if n_clicks:                            dfgb = df.groupby(['state']).sum()return dfgb.to_dict('rows')if __name__ == '__main__':application.run(debug=False, port=8080)
Answer

When you are trying to register the callback Output component as a DataTable, all the required / mandatory attributes for the DataTable component should be updated in the callback and returned. In your code, you are updating just DataTable.data and not DataTable.column, one easy way is to return the whole Datatable component which is prepopulated with all the required attribute values.

Here is an example,

import dash_html_components as html
import dash_core_components as dcc
import dash
import dash_table
import pandas as pd
import dash_table_experiments as dtapp = dash.Dash(__name__)#data to be loaded
data = [['Alex',10],['Bob',12],['Clarke',13],['Alex',100]]
df = pd.DataFrame(data,columns=['Name','Mark'])app.layout = html.Div([dt.DataTable(rows=df.to_dict('records'),columns=df.columns,row_selectable=True,filterable=True,sortable=True,selected_row_indices=list(df.index),  # all rows selected by defaultid='2'),html.Button('Submit', id='button'),html.Div(id="div-1"),
])@app.callback(dash.dependencies.Output('div-1', 'children'),[dash.dependencies.Input('button', 'n_clicks')])
def update_output(n_clicks):df_chart = df.groupby('Name').sum()return [dt.DataTable(rows=df_chart.to_dict('rows'),columns=df_chart.columns,row_selectable=True,filterable=True,sortable=True,selected_row_indices=list(df_chart.index),  # all rows selected by defaultid='3')]if __name__ == '__main__':app.run_server(debug=True)

Looks like dash-table-experiments is deprecated.

Edit 1: Here is one way of how it can be achieved using dash_tables

import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
from dash.dependencies import Input, Output, Statedf = pd.read_csv('https://gist.githubusercontent.com/chriddyp/''c78bf172206ce24f77d6363a2d754b59/raw/''c353e8ef842413cae56ae3920b8fd78468aa4cb2/''usa-agricultural-exports-2011.csv')app = dash.Dash()
application = app.serverapp.layout = html.Div([dt.DataTable(id = 'dt1', columns =  [{"name": i, "id": i,} for i in (df.columns)],),html.Div([html.Button(id='submit-button',                children='Submit')]),    ])@app.callback(Output('dt1','data'),[Input('submit-button','n_clicks')],[State('submit-button','n_clicks')])def update_datatable(n_clicks,csv_file):            if n_clicks:                            dfgb = df.groupby(['state']).sum()data_1 = df.to_dict('rows')return data_1if __name__ == '__main__':application.run(debug=False, port=8080)

Another way: return the whole DataTable

import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
from dash.dependencies import Input, Output, Statedf = pd.read_csv('https://gist.githubusercontent.com/chriddyp/''c78bf172206ce24f77d6363a2d754b59/raw/''c353e8ef842413cae56ae3920b8fd78468aa4cb2/''usa-agricultural-exports-2011.csv')app = dash.Dash()
application = app.serverapp.layout = html.Div([html.Div(id="table1"),html.Div([html.Button(id='submit-button',                children='Submit')]),    ])@app.callback(Output('table1','children'),[Input('submit-button','n_clicks')],[State('submit-button','n_clicks')])def update_datatable(n_clicks,csv_file):            if n_clicks:                            dfgb = df.groupby(['state']).sum()data = df.to_dict('rows')columns =  [{"name": i, "id": i,} for i in (df.columns)]return dt.DataTable(data=data, columns=columns)if __name__ == '__main__':application.run(debug=False, port=8080)

I referred to this example: https://github.com/plotly/dash-table/blob/master/tests/cypress/dash/v_copy_paste.py#L33

https://en.xdnf.cn/q/70975.html

Related Q&A

Nose: How to skip tests by default?

I am using Pythons nose and I have marked some of my tests as "slow", as explained in the attrib plugin documentation.I would like to skip all "slow" Tests by default when running n…

SQLAlchemy ORM select multiple entities from subquery

I need to query multiple entities, something like session.query(Entity1, Entity2), only from a subquery rather than directly from the tables. The docs have something about selecting one entity from a s…

How to ensure data is received between commands

Im using Paramiko to issue a number of commands and collect results for further analysis. Every once in a while the results from the first command are note fully returned in time and end up in the out…

Format Excel Column header for better visibility and Color

I have gone through many posts but did not found the exact way to do the below. Sorry for attaching screenshot(Just for better visibility) as well , I will write it also. Basically it looks like -Name…

Using multiple keywords in xattr via _kMDItemUserTags or kMDItemOMUserTags

While reorganizing my images, in anticipation of OSX Mavericks I am writing a script to insert tags into the xattr fields of my image files, so I can search them with Spotlight. (I am also editing the …

JAX Apply function only on slice of array under jit

I am using JAX, and I want to perform an operation like @jax.jit def fun(x, index):x[:index] = other_fun(x[:index])return xThis cannot be performed under jit. Is there a way of doing this with jax.ops …

Using my own corpus for category classification in Python NLTK

Im a NTLK/Python beginner and managed to load my own corpus using CategorizedPlaintextCorpusReader but how do I actually train and use the data for classification of text?>>> from nltk.corpus…

Python ImportError for strptime in spyder for windows 7

I cant for the life of me figure out what is causing this very odd error.I am running a script in python 2.7 in the spyder IDE for windows 7. It uses datetime.datetime.strptime at one point. I can run …

How to show diff of two string sequences in colors?

Im trying to find a Python way to diff strings. I know about difflib but I havent been able to find an inline mode that does something similar to what this JS library does (insertions in green, deletio…

Regex for timestamp

Im terrible at regex apparently, it makes no sense to me...Id like an expression for matching a time, like 01:23:45 within a string. I tried this (r(([0-9]*2)[:])*2([0-9]*2)but its not working. I need …