Black Lives Matter. Please consider donating to Black Girls Code today.

Calculation in Dash Table Columns

Hi Guys,

Could you please take a look in my code and give me some guide how resolve some issues.
I creating a Dash Table from poandas dataframe:

html.Div([
   html.H2(children = "Tabela De Suporte Ao Planejamento",
    style = {'textAlign' : 'center',}),
]),    
html.Div([
    dash_table.DataTable(
        id='computed-table',
        columns=[{"name": i, "id": i} for i in dfplano.columns],
        editable={'UPH_BPI_vs_Perfil': True, 'Head_Disponível': True,
                  'OrderType': False, 'Unidades Pendentes': False, 'UnidadesProcessadas': False, 
                  'UPH_BPI vs Head':False, 'Qty': False},
         data=dfplano.to_dict('records'),
        style_table={'textAlign': 'center'},
         style_as_list_view=True,
        style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
        style_header={
            'backgroundColor': 'white',
            'fontWeight': 'bold',
            'fontSize': 12},


    ),

        ],style={'textAlign': 'center',
                 'align-items': 'center',
                 'fontSize': 12,
                 'width': '100%',
                 'display': 'flex',
                 'align-items': 'center',
                 'justify-content': 'center'}),   

And i have a call back where i want to perform calculations in column “UPH_BPI vc Head” and “ETA Geral” with valoes in another columns.
For this, i created callback below.

@app.callback(
    Output('computed-table', 'data'),
    [Input('computed-table', 'data_timestamp')],
    [State('computed-table', 'data')])
def update_columns(timestamp, rows):
    for row in rows:
        try:
            row['UPH_BPI_vs_Head'] = float(row['Head_Disponíve']) * float(row['UPH_BPI_vs_Perfil'])
            row['ETA Geral'] = float(row['Unidades Pendentes']) / float(row['UPH_BPI_vs_Head'])
        except:
            row['UPH_BPI vs Head'] = 'NA'
            row['ETA Geral'] = 'NA'
    return rows

My issues is.
1 - Calculations are not being performed.
2 - All Fields from table are editable, same after i set up as false.

Could you please help me?
Thanks?

Calcs are not being done as data_timestamp is not a callback trigger event. You need to add a component that can trigger an event and add this to your callback.

I use this as base, Dash community fix guide.

@app.callback(
    Output('computed-table', 'data'),
    [Input('computed-table', 'data_timestamp')],
    [State('computed-table', 'data')])
def update_columns(timestamp, rows):
    for row in rows:
        try:
            row['output-data'] = float(row['input-data']) ** 2
        except:
            row['output-data'] = 'NA'
    return rows


if __name__ == '__main__':
    app.run_server(debug=True)

could you please advise a valid method to perform these calculations?

So your callback is being called one time - on page load. But that is independent of your data_timestamp input. I cannot find any documentation that this will trigger post-page load.

Regarding your calculations. I converted your rows variable back to a panda df, performed a computation and returned the new dataframe. Since I added a new column, I needed to update the table’s column component.

NOTE: I created a dummy dataframe since your sample code didn’t specify its construct.

Also, in the callback I added code to indicate which Input triggered it.

import dash
from dash.dependencies import Input, Output, State
import dash_table
import dash_html_components as html
import pandas as pd

app = dash.Dash()
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')

app.layout = html.Div([
    html.Div(
        [
        html.H2(children="Tabela De Suporte Ao Planejamento",
                style={'textAlign': 'center', }),
        ]
    ),
    html.Div([
        dash_table.DataTable(
            id='computed-table',
            columns=[{"name": i, "id": i} for i in df.columns],
            # editable={'UPH_BPI_vs_Perfil': True, 'Head_Disponível': True,
            #           'OrderType': False, 'Unidades Pendentes': False, 'UnidadesProcessadas': False,
            #           'UPH_BPI vs Head': False, 'Qty': False},
            data=df.to_dict('records'),
            style_table={'textAlign': 'center'},
            style_as_list_view=True,
            style_cell={'padding': '5px', 'fontSize': 12, 'textAlign': 'center'},
            style_header={
                'backgroundColor': 'white',
                'fontWeight': 'bold',
                'fontSize': 12},

        )],
        style={'textAlign': 'center',
               'fontSize': 12,
               'width': '100%',
               'display': 'flex',
               'align-items': 'center',
               'justify-content': 'center'}
    ),
])


@app.callback(
    [Output('computed-table', 'data'),
     Output('computed-table', 'columns')],
    [Input('computed-table', 'data_timestamp')],
    [State('computed-table', 'data')])
def update_columns(timestamp, rows):
    ctx = dash.callback_context
    triggered_input = ctx.triggered[0]['prop_id'].split('.')[0]
    print('Callback reached | trigger = {}'.format(triggered_input))

    table_data = df.from_dict(rows)
    try:
        table_data['output-row'] = table_data['Installed Capacity (MW)'] * table_data['Generation (GWh)']
    except:
        table_data['output-row'] = 'NA'

    new_cols = [{"name": i, "id": i} for i in table_data.columns]
    return table_data.to_dict('records'), new_cols


if __name__ == '__main__':
    app.run_server(debug=True)

@flyingcujo,

I see, thank you for explain.

But my problem is, i need to be able to edir values direct in column of Dash Table, and also another colum perform calculations with this value and another that became from dataframe.

Any idea how can i proceed? any method?

In this code your colurms are not editable, how can i define specific columns as editable if columns become from dataframe?

In your code sample, how can i setup column “Installed Capacity (MW)” as editable?