Dash Ag Grid Pivot Example

Hi @hoatran

You can find more info in the AG Grid docs since there are not too many examples in the dash docs yet:

Here’s an example using the data you provided (Thanks that was helpful):

import pandas as pd
import numpy as np
import dash_ag_grid as dag
from dash import Dash, html, dcc

#create DataFrame
df = pd.DataFrame({'name': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'g'],
                   'school': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   'Date' : ['20230809', '20230809', '20230809', '20230809', '20230809', '20230809', '20230809', '20230809', '20230809'],
                   'points': [2800, 1700, 1900, 1400, 2300, 2600, 5000, 10000, 15000],
                   'rebounds': [5000, 6000, 4000, 7000, 14000, 12000, 9000, 3000, 9000],
                   'assists': [10000, 13000, 7000, 8000, 4000, 5000, 8000, 10000, 7000]})

df_pivot = pd.pivot_table(df, values='points', index=['Date'], columns = ['school', 'name'], aggfunc=np.sum).reset_index()

app = Dash(__name__)

columnDefs = [
    {"field": "school", "pivot": True},
    {"field": "name", "pivot": True},
    {"field": "Date", "rowGroup": True},
    {"field": "points", "aggFunc": "sum"},
    {"field": "rebounds"},
    {"field": "assists"},
]

defaultColDef = {
    "flex": 1,
    "minWidth": 150,
}


app.layout = html.Div(
    [

        dag.AgGrid(
            id="pivot-ag-grid-example",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            dashGridOptions={
                "suppressExpandablePivotGroups": True,
                "pivotMode": True,
            },
            defaultColDef=defaultColDef,
            # Pivot groupings is an ag-grid Enterprise feature.
            # A license key should be provided if it is used.
            # License keys can be passed to the `licenseKey` argument of dag.AgGrid
            enableEnterpriseModules=True,

        ),
    ]
)


if __name__ == "__main__":
    app.run(debug=True)
6 Likes