dash datatable

Published by onesixx on

https://dash.plotly.com/datatable

React.js 기반

from dash import Dash, dash_table
import dash_bootstrap_components as dbc

import pandas as pd

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

app = Dash(__name__)

app.layout = dbc.Container([
    dash_table.DataTable(
        data=df.to_dict('records'),
        #columns=[{"name": i, "id": i} for i in df.columns]
    ),
    dbc.Alert(id='tbl_out'),
])

print("========data=======")
print(df.to_dict('records'))
print("========columns=======")
print([{"name": i, "id": i} for i in df.columns])

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

jjjjjj

import pandas as pd

df = pd.DataFrame([
    ['Jay', 16,   'BBA'],
    ['Jack',19, 'BTech'],
    ['Mark',18,   'BSc']],
    columns = ['Name','Age','Course'])


dd = pd.concat([   
    pd.Series(['Jay', 'Jack', 'Mark']),
    pd.Series([16,19,18]),
    pd.Series(['BBA', 'BTech', 'BSc'])], 
    axis =1,
    names = ['Name','Age','Course']
) 
dd.columns = ['Name','Age','Course']

#   Name\tAge\tCourse
# 0\tJay\t    16\tBBA
# 1\tJack\t19\tBTech
# 2\tMark\t18\tBSc

#------------------------------------------------------
# ('dict', list, 'series', 'split', 'records', 'index')
dd.to_dict()
dd.to_dict('dict')
# {'Name'  : {0: 'Jay', 1: 'Jack',  2: 'Mark'},
#  'Age'   : {0: 16,    1: 19,      2: 18},
#  'Course': {0: 'BBA', 1: 'BTech', 2: 'BSc'}}

dd.to_dict('list')  
# {'Name'  : ['Jay', 'Jack', 'Mark'],
#  'Age'   : [16, 19, 18],
#  'Course': ['BBA', 'BTech', 'BSc']}

dd.to_dict('records')
# [{'Name': 'Jay',  'Age': 16, 'Course': 'BBA'},
#  {'Name': 'Jack', 'Age': 19, 'Course': 'BTech'},
#  {'Name': 'Mark', 'Age': 18, 'Course': 'BSc'}]

dd.to_dict('split')
# {'index': [0, 1, 2],
#  'columns': ['Name', 'Age', 'Course'],
#  'data': [['Jay', 16, 'BBA'], ['Jack', 19, 'BTech'], ['Mark', 18, 'BSc']]}

dd.to_json(orient='split')
# '{"columns":["Name","Age","Course"],
#   "index":[0,1,2],
#   "data":[["Jay",16,"BBA"],["Jack",19,"BTech"],["Mark",18,"BSc"]]}'

https://dash.plotly.com/datatable

React.js 

Introduction to Dash DataTable – Growing a Spreadsheet into an Application

Quickstart

an interactive table component designed for viewing, editing, and exploring large datasets.

>>> help(dash.dash_table.DataTable)
import sys, os
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.pkg_ui import *

from dash import dash_table as dt
from dash.dash_table.Format import Group

#'https://raw.githubusercontent.com/plotly/datasets/master/solar.csv'
URL_DATA = 'https://git.io/Juf1t'
df = pd.read_csv(URL_DATA)

app = dash.Dash(__name__)

app.layout = dac.Page(children=[
    dt.DataTable(id='table',
        columns=[{"id":i, "name":i} for i in df.columns],
        data=df.to_dict('records'),
        editable=True
    )
])

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

Table with click callback

import sys, os
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.pkg_ui import *

from dash import dash_table as dt
from dash import Dash, Input, Output, callback

df = pd.read_csv('https://git.io/Juf1t')
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(children=[
    dbc.Label('Click a cell in the table'),
    dt.DataTable(id='tbl',
        columns=[{"id":i, "name":i} for i in df.columns],
        data=df.to_dict('records'),
        editable=True
    ),
    dbc.Alert(id='tbl_out')
])

@callback(
    Output('tbl_out', 'children'),
    Input('tbl', 'active_cell')
) 
def update_graphs(active_cell):
    return str(active_cell) if active_cell else "Click the table"

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

Styling & Fommatting

Height

height with vertical scroll, pagination, virtualization, and fixed headers.

cf. Backend Paging

Width

  • style_cell : data cells & the header cells.
  • style_header : header styles
  • style_data : data cell styles

Styling

The style of the DataTable is highly customizable.

  • Displaying multiple rows of headers
  • Text alignment
  • Styling the table as a list view
  • Changing the colors (including a dark theme!)
...

app.layout = dbc.Container(children=[
    dt.DataTable(id='tbl',
        columns=[{"id":i, "name":i} for i in df.columns],
        data=df.to_dict('records'),
        editable=True,
                 
        ## 10줄씩 묶어 pageination (default는 250줄)
        page_size=10         
                 
        ## pagination없이 무한 스크롤 (row 1000개 이상은 사용금지!!)
        page_action='none',
        style_table={'height':'300px', 'overflowY':'auto'}
        
        ## pagination + 스크롤
        page_size=20,  
        style_table={'height': '300px', 'overflowY': 'auto'},
        fixed_rows={'headers': True},
        
        ##
        virtualization=True,

    \tfixed_rows={'headers': True},
    \tstyle_cell={'minWidth': 95, 'width': 95, 'maxWidth': 95},
    \tstyle_table={'height': 300}  # default is 500
                 
        ## width - word wrep
        style_data={
        \t'whiteSpace': 'normal',
        \t'height': 'auto',
            
            'lineHeight': '15px'
    \t},
                 
        # width conditional
        style_data={
        \t'width': '100px',
        \t'maxWidth': '100px',
        \t'minWidth': '100px',
        },
        style_cell_conditional=[
        \t{
            \t'if': {'column_id': 'Region'},
            \t'width': '250px'
        \t}
        ],
        style_table={
            'overflowX': 'auto'
        }
                 
        ### Style - Column Alignment
        style_cell={
            'padding': '5px'
        },
        style_as_list_view=True,
        style_header={
            'backgroundColor': 'lightgrey',
            'fontWeight': 'bold'
        },
        style_data={
            'color': 'black',
            'backgroundColor': 'white'
        },
        style_data_conditional=[
            {
                'if': {'row_index': 'odd'},
                'backgroundColor': 'rgb(220, 220, 220)',
            }
        ],
        ### Style - Column Alignment
        style_cell_conditional=[
            {
                'if': {'column_id': c},
                'textAlign': 'left'
            } for c in ['Date', 'Region']
        ],
    ),
   
])

...

Conditional Formatting

Several examples of how to highlight certain cells, rows, or columns based on their value or state.

Number Formatting

Several examples of how to format and localize numbers.

config를 활용한 Styling

dt_style={ 
    'style_as_list_view' : True,
    'style_header' : {
        'backgroundColor': 'lightgrey',
        'fontWeight': 'bold',
        'textAlign':'center',
    },
    'style_data' : {
        'color': 'black',
        'backgroundColor': 'white'
    }
}
...
from common.config import dt_style
...

app.layout = dbc.Container(children=[
    dt.DataTable(id='tbl',
        columns=[{"id":i, "name":i} for i in df.columns],
        data=df.to_dict('records'),

        **dt_style   
    ),
])

...

Interactive DataTable

Sorting, Filtering, Selecting, and Paging Natively

. This chapter demonstrates the interactive features of the table and how to wire up these interations to Python callbacks. These actions include:

  • Paging
  • Selecting Rows
  • Sorting Columns
  • Filtering Data
import sys, os
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.pkg_ui import *
from common.config import dt_style

from dash import dash_table as dt
from dash import Dash, Input, Output, callback
import random

data ='https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv' 
df = pd.read_csv(data)

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dbc.Container(children=[
    dbc.Label('gapminder: 국가별 경제/의료 수준 DataSet (rm year)'),
    html.Div(id='datatable-interactivity-container'),
    dt.DataTable(id='tbl',
        columns=[{"id":i, "name":i} for i in df.columns],
        data=df.to_dict('records'),
        # editable=False,
        filter_action="native",

        sort_action="native",
        sort_mode="multi",

        column_selectable="single",
        selected_columns=[],

        row_selectable="multi",
        selected_rows=[],

        page_action="native",
        page_size=10,
        **dt_style   
    ),

])

@app.callback(
    Output('tbl', 'style_data_conditional'),
    Input('tbl', 'selected_columns')
)
def update_styles(selected_columns):
    return [{
        'if': { 'column_id': i },
        'background_color': '#D2F3FF'
    } for i in selected_columns]

@app.callback(
    Output('datatable-interactivity-container', "children"),
    Input('tbl', "derived_virtual_data"),
    Input('tbl', "derived_virtual_selected_rows"))
def update_graphs(rows, derived_virtual_selected_rows):
    dff = df if rows is None else pd.DataFrame(rows)
    if derived_virtual_selected_rows is None:
        derived_virtual_selected_rows = []

    colors = ['lightskyblue' if i in derived_virtual_selected_rows else 'royalblue'
              for i in range(len(dff))]
    return [
        dcc.Graph(id=column,
            figure={
                "data": [
                    {
                        "x": dff["country"], "y": dff[column],
                        "type": "bar", "marker": {"color": colors},
                    }
                ],
                "layout": {
                    "xaxis": {"automargin": True},
                    "yaxis": {
                        "automargin": True,
                        "title": {"text": column}
                    },
                    "height": 250,
                    "margin": {"t": 10, "l": 10, "r": 10},
                },
            },
        ) for column in ["pop", "lifeExp", "gdpPercap"] if column in dff
    ]

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

DataTable Tooltips

Display tooltips on data and header rows, conditional tooltips, define tooltips for each cell, customize behavior.

Python-Driven Filtering, Paging, Sorting

In Part 3, the paging, sorting, and filtering was done entirely clientside (in the browser). This means that you need to load all of the data into the table up-front. If your data is large, then this can be prohibitively slow. In this chapter, you’ll learn how to write your own filtering, sorting, and paging backends in Python with Dash. We’ll do the data processing with Pandas but you could write your own routines with SQL or even generate the data on the fly!Editable DataTable

The DataTable is editable. Like a spreadsheet, it can be used as an input for controlling models with a variable number of inputs. This chapter includes recipes for:

  • Determining which cell has changed
  • Filtering out null values
  • Adding or removing columns
  • Adding or removing rows
  • Ensuring that a minimum set of rows are visible
  • Running Python computations on certain columns or cells

Typing and User Input Processing

In this chapter, you’ll learn how to configure the table to

  • assign the column type
  • change the data presentation
  • change the data formatting
  • validate or coerce user data input
  • apply default behavior for valid and invalid data

Dropdowns Inside DataTable

Cells can be rendered as editable Dropdowns. This is our first stake in bringing a full typing system to the table. Rendering cells as dropdowns introduces some complexity in the markup and so there are a few limitations that you should be aware of.Virtualization

Examples using DataTable virtualization.Filtering Syntax

An explanation and examples of filtering syntax for both frontend and backend filtering in the DataTable.Dash Python > Dash DataTable

Categories: dash

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x