Paginating a key stats table

The key stats table created in the previous lesson was a great addition to the analytical toolkit of the global e-commerce company. However, it was far too long!

Let's fix that using Dash Data Table's built-in pagination options. This will greatly enhance the usability of the app and allow users to explore different sections of the data as they require.

Este exercício faz parte do curso

Building Dashboards with Dash and Plotly

Ver Curso

Instruções de exercício

  • Create a Dash Data Table object below line 21.
  • Add pagination to the Data Table using Dash's built-in pagination functionality below line 28.
  • Start the pagination on the first page of data below line 30.
  • Ensure each page renders 7 rows of data below line 32.

Exercício interativo prático

Experimente este exercício preenchendo este código de exemplo.

import dash
from dash import dcc, html
import plotly.express as px
import dash_table
from dash_table import DataTable, FormatTemplate
import pandas as pd
from dash.dependencies import Input, Output
ecom_sales = pd.read_csv('/usr/local/share/datasets/ecom_sales.csv')
logo_link = 'https://assets.datacamp.com/production/repositories/5893/datasets/fdbe0accd2581a0c505dab4b29ebb66cf72a1803/e-comlogo.png'
key_stats_tb = ecom_sales.groupby(['Country','Major Category', 'Minor Category'])['OrderValue'].agg(['sum', 'count', 'mean']).reset_index().rename(columns={'count':'Sales Volume', 'sum':'Total Sales ($)', 'mean':'Average Order Value ($)'})

money_format = FormatTemplate.money(2)
money_cols = ['Total Sales ($)', 'Average Order Value ($)']
data_cols = [x for x in key_stats_tb.columns if x not in money_cols]
d_columns = [{'name': x, 'id': x} for x in data_cols]
d_columns +=[{'name': x, 'id': x, 
              'type':'numeric', 'format': money_format
  			} for x in money_cols]

# Create a Data Table
d_table = DataTable(
            columns=d_columns,
            data=key_stats_tb.to_dict('records'),
            cell_selectable=False,
            sort_action='native',
            filter_action='native',
            # Add pagination
            ____='____',
            # Start on the first page
            ____=0,
            # Render 7 items per page
            ____=____,
            )

app = dash.Dash(__name__)

app.layout = html.Div([
  html.Img(src=logo_link, 
        style={'margin':'30px 0px 0px 0px' }),
  html.H1('Sales Aggregations'),
  html.Div(
    children=[
      html.H2('Key Aggregations'),
      d_table
      ],
      style={'width':'850px', 'height':'750px', 'margin':'0 auto'}
    ),
    ], 
  style={'text-align':'center', 'display':'inline-block', 'width':'100%'}
  )

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