Do not understand this sorting example in dashtable!

Hi All,

I am really confused on how to sort in dash table.I am following the documentation on the plotly website and am applying it my own df yet it doens’t seem to work. I feel i am missing some basics such as what is sort_by=[]? How does this then get used in: dff = df.sort_values(sort_by[0][‘column_id’],ascending=sort_by[0][‘direction’] == ‘asc’,inplace=False) in this line- I don’t get where ‘column_id’ comes from or ‘direction’?? df in the example below is my own df. Please see my comments below i am really confused !

df[' index'] = range(1, len(df) + 1) # Why do we add this?

app = dash.Dash(__name__)

PAGE_SIZE = 5

app.layout = dash_table.DataTable(
    id='table-paging-and-sorting',
    columns=[
        {'name': i, 'id': i, 'deletable': True} for i in sorted(df.columns)
    ],
    page_current=0,
    page_size=PAGE_SIZE,
    page_action='custom',

    sort_action='custom',
    sort_mode='single',
    sort_by=[]
)


@app.callback(
    Output('table-paging-and-sorting', 'data'),
    [Input('table-paging-and-sorting', "page_current"), # How do i know what to put in input??
     Input('table-paging-and-sorting', "page_size"),
     Input('table-paging-and-sorting', 'sort_by')])
def update_table(page_current, page_size, sort_by):
    if len(sort_by):
        dff = df.sort_values(
            sort_by[0]['column_id'],
            ascending=sort_by[0]['direction'] == 'asc',
            inplace=False
        )
    else:
        # No sort is applied
        dff = df

    return dff.iloc[
        page_current*page_size:(page_current+ 1)*page_size
    ].to_dict('records')


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

im unsure on what sort_by[0][‘column_id’] means, i.e. where did column_id come from?

1 Like