ITables

Turn a pandas or polars data frame into a searchable, sortable, exportable DataTable that drives the rest of your app.

ITables brings DataTables, the JavaScript table library, to pandas and polars. Return a data frame, or an ITable with options like select=True, buttons=[...], or column_filters="header", and @render_itables shows it sized to fill its card.

hero

A table, a continent filter, and a plotly scatter plot, kept in sync by one selection. Try the app.

Installation

pip install 'shinywidgets[itables]'

This installs itables[widget] (itables plus anywidget, which the Shiny integration requires).

Quick start

from __future__ import annotations

import plotly.express as px
from itables.widget import ITable
from shiny.express import ui
from shinywidgets import render_itables

countries = px.data.gapminder().query("year == 2007")[
    ["country", "continent", "lifeExp", "pop", "gdpPercap"]
].reset_index(drop=True)

ui.page_opts(title="itables quickstart", fillable=True)

with ui.card(full_screen=True):
    ui.card_header("142 countries, 2007 (click a row to select it)")

    @render_itables
    def table():
        return ITable(countries, select=True)

quickstart

Returning a data frame directly (no ITable(...)) also works, but select=True and every other itables option require constructing an ITable explicitly.

Overview

A look at what you can build. Click any of them to open the app, with its code, in Shinylive.

DataTables’ full extension catalog – SearchPanes, SearchBuilder, RowGroup, FixedColumns, and more – works through the same keyword options; see itables.org for the complete list.

Table features

Each of the following is a plain itables/DataTables option – nothing Shiny-specific yet.

Search and column filters

DataTables’ global search box is on by default. Add column_filters="header" for a text input per column – useful once a table has more than a handful of columns and a single search box starts returning too much.

examples/02_search_and_filters.pyexcerpt · 5 of 21 lines
    @render_itables
    def table():
        # The global search box is on by default; column_filters adds one text
        # input per column, wired to DataTables' own column search.
        return ITable(countries, column_filters="header", select=True)

search and filters

SearchPanes

For a categorical column, SearchPanes draws a checkbox panel with a live row count per value – closer to a BI tool’s filter pane than a text box.

examples/03_search_panes.pyexcerpt · 11 of 27 lines
    @render_itables
    def table():
        # SearchPanes draws a faceted filter panel (one pane per listed column,
        # with row counts) above the table; checking a value filters like a
        # column search would.
        return ITable(
            countries,
            layout={"top1": "searchPanes"},
            searchPanes={"layout": "columns-1", "columns": [1]},
            select=True,
        )

Export buttons

The Buttons extension adds copy-to-clipboard and CSV/Excel export, with no server round trip – the browser already has the data.

examples/04_buttons_export.pyexcerpt · 3 of 19 lines
    @render_itables
    def table():
        return ITable(countries, buttons=["copyHtml5", "csvHtml5"], select=True)

buttons

Cell formatting and conditional styling

columnDefs accepts a DataTables render (reformat a cell’s display value) or createdCell (restyle the cell) as a JavascriptFunction. It runs in the browser, as the user sorts, searches, and pages. DataTables’ own JS recipes, such as $.fn.dataTable.render.number(...), work as written.

examples/05_styling.pyexcerpt · 33 of 50 lines
    @render_itables
    def table():
        return ITable(
            countries,
            columnDefs=[
                {
                    # Format gdpPercap (column index 4) as currency on display,
                    # but keep the raw number for sorting/filtering.
                    "targets": [4],
                    "render": JavascriptFunction(
                        "function(data, type) {"
                        "  return type === 'display' "
                        "    ? '$' + Number(data).toLocaleString() : data;"
                        "}"
                    ),
                },
                {
                    # Color the life-expectancy cell by value. Without a
                    # `render` of its own, this column's cell data arrives as
                    # itables' own [display_string, raw_number] pair, not a
                    # plain number -- index into it rather than comparing it
                    # directly.
                    "targets": [2],
                    "createdCell": JavascriptFunction(
                        "function(td, data) {"
                        "  var v = Array.isArray(data) ? data[1] : data;"
                        "  td.style.color = v < 60 ? '#c0392b'"
                        "    : v >= 75 ? '#1e8449' : '';"
                        "}"
                    ),
                },
            ],
        )

styling

In a numeric column without its own render, createdCell receives a [display_string, raw_number] pair, not a number, so compare data[1] as above; data < 60 is always false.

pandas Styler, rendered as-is

Pass a Styler (e.g. from .style.background_gradient() or .format()) with allow_html=True, and itables renders its computed HTML and inline styles unchanged – gradients, bold, custom number formats, anything Styler can produce. allow_html=True means the content is trusted; don’t point it at user-supplied HTML.

examples/06_pandas_styler.pyexcerpt · 9 of 25 lines
    @render_itables
    def table():
        styler = (
            countries.style.background_gradient(subset=["lifeExp"], cmap="RdYlGn")
            .format({"lifeExp": "{:.1f}", "gdpPercap": "${:,.0f}", "pop": "{:,.0f}"})
        )
        # A Styler always carries HTML (its inline styles), so itables requires
        # an explicit opt-in to render it.
        return ITable(styler, allow_html=True, select=True)

pandas styler

polars, unchanged

ITable accepts a polars DataFrame directly – no conversion to pandas. selected() still returns plain positions, so index the polars frame the usual way (pl_df[rows]):

from __future__ import annotations

import plotly.express as px
import polars as pl
from itables.widget import ITable
from shiny.express import render, ui
from shinywidgets import render_itables

countries = pl.from_pandas(
    px.data.gapminder()
    .query("year == 2007")[["country", "continent", "lifeExp", "pop", "gdpPercap"]]
    .reset_index(drop=True)
)

ui.page_opts(title="polars", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_itables
        def table():
            # itables accepts a polars DataFrame directly; no pandas conversion
            return ITable(countries, select=True)

    with ui.card():
        ui.card_header("Selected rows (polars indexing)")

        @render.data_frame
        def selected():
            return countries[table.selected()]

polars

Reacting to interaction

Every @render_itables output has one accessor, table.selected(), a list of the positions the user has clicked. Call it from any reactive context, the same way you’d call input.my_slider(), and that context re-runs whenever the selection changes.

Click a row for detail

examples/12_selection_detail_card.pyexcerpt · 13 of 36 lines
        @render.ui
        def detail():
            rows = table.selected()
            if not rows:
                return ui.p("Click a row to see its detail.")
            row = countries.iloc[rows[-1]]
            return ui.TagList(
                ui.h5(row["country"]),
                ui.p(f"Continent: {row['continent']}"),
                ui.p(f"Life expectancy: {row['lifeExp']:.1f} years"),
                ui.p(f"Population: {row['pop']:,}"),
                ui.p(f"GDP per capita: ${row['gdpPercap']:,.0f}"),
            )

selected() is [] until the user clicks a row, so handle that case, as above.

Updating in place

A re-render (returning a new value from the decorated function) is the simplest way to reflect a changed input, but it rebuilds the DataTables instance from scratch: sort, search, scroll position, and selection all reset. For everything else – selecting rows programmatically, swapping in new data, filtering without losing the selection – update table.widget in place from a @reactive.effect instead.

Selecting rows programmatically

Set .selected_rows directly for the same effect as a click:

@reactive.effect
@reactive.event(input.top5)
def _select_top5():
    # Setting .selected_rows on the widget highlights those rows in the
    # browser immediately, exactly as if the user had clicked them -- no
    # re-render, so sort/search/scroll state is untouched.
    top5 = countries.nlargest(5, "pop").index.tolist()
    table.widget.selected_rows = top5

Swapping the data

.widget.update(df, **options) replaces the data in place, so the sort column and scroll position survive. update() drops options like columnDefs and buttons unless you pass them again, so keep them in one dict and reuse it:

examples/13_update_in_place.pyexcerpt · 12 of 30 lines
    @render_itables
    def table():
        return ITable(countries, select=True, buttons=["copyHtml5"])


@reactive.effect
@reactive.event(input.shrink)
def _shrink():
    top10 = countries.nlargest(10, "pop")
    # Re-passing `buttons` matters: .update(df) without it silently drops the
    # button row (and any columnDefs) that the original ITable(...) call set.
    table.widget.update(top10, buttons=["copyHtml5"])

Filtering, with the selection preserved

Positions survive a filter only if you remap them by a stable key:

# The current (possibly continent-filtered) rows. Positions from
# table.selected() are only meaningful against whatever data frame is
# currently shown, so track it here (ITable.update(df) doesn't expose its
# current data frame for reading it back).
current_rows = reactive.value(countries)


@reactive.effect
def _filter():
    continent = input.continent()
    req(table.widget)
    with reactive.isolate():
        shown = (
            countries
            if continent == "All"
            else countries[countries["continent"] == continent]
        )
        # Positions are into `shown`, so re-map the current selection by a
        # stable key (country name) instead of keeping the old positions,
        # which would now point at different rows (or be out of range).
        kept = set(current_rows().iloc[table.selected()]["country"])
        remapped = [i for i, c in enumerate(shown["country"]) if c in kept]
        table.widget.update(shown, selected_rows=remapped, **TABLE_OPTS)
        current_rows.set(shown)

Linking widgets

Selection highlights a plot

Read table.selected() in an effect and write the result into another widget’s trait, inside reactive.isolate() so the write doesn’t re-trigger the effect:

@reactive.effect
def _highlight_selection():
    selected = set(table.selected())
    with reactive.isolate():
        # In place: the scatter keeps its zoom/pan state across selections,
        # instead of rebuilding (and resending) the whole figure.
        scatter.widget.data[0].marker.color = [
            "#e41a1c" if i in selected else "#bbb" for i in range(len(countries))
        ]

The same pattern works with any widget that has a trait you can set, not only plotly.

Accessor reference

Accessor Returns Before any interaction Across a re-render Default rate policy
selected() list[int] [], or the table’s selected_rows= The new table’s selection ([] unless it sets selected_rows=) none

A plain @render_widget returning an ITable also works, with the same sizing but without .selected().

selected()

Positions index the table’s data, not its display, so they survive sorting, searching, and paging. A re-render resets them. .widget.update(df) doesn’t: the old positions now point into the new data and can select the wrong rows. If the data can change, track selections by an ID column, as in Filtering, with the selection preserved.

examples/08_selected_rows_accessor.pyexcerpt · 19 of 32 lines
with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_itables
        def table():
            return ITable(countries, select=True)

    with ui.card():
        ui.card_header("table.selected()")

        @render.code
        def rows():
            return str(table.selected())

        @render.data_frame
        def selected():
            # Positions are into the data, not the display: they survive
            # sorting and searching.
            return countries.iloc[table.selected()]

Click two rows, then sort by life expectancy and click the new first row – the position tracks the row, not the screen location:

Tuning accessors

Reading on demand

selected() is live from the moment the table renders, whether or not anything has read it yet. So you can leave it unread until a button click or a download handler needs it – the rows the user selected earlier aren’t lost:

import io

import plotly.express as px
from itables.widget import ITable
from shiny.express import render, ui
from shinywidgets import render_itables

ui.page_opts(title="Read on demand: export selected rows", fillable=True)

countries = px.data.gapminder().query("year == 2007")[
    ["country", "continent", "lifeExp", "pop", "gdpPercap"]
].reset_index(drop=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_itables
        def table():
            return ITable(countries, select=True)

    with ui.card():
        ui.card_header("Export")
        ui.p("Click some rows, then download -- no need to read selected() anywhere else first.")

        # selected() is live from the moment the table renders, whether
        # or not anything has read it yet, so this handler can read it cold,
        # the instant the user clicks download: no warm-up reader required.
        @render.download_button(filename="selected_countries.csv", label="Download selected as CSV")
        def download_csv():
            rows = table.selected()
            buf = io.StringIO()
            countries.iloc[rows].to_csv(buf, index=False)
            yield buf.getvalue()

Rate limiting

examples/09_rate_limiting.pyexcerpt · 31 of 50 lines
with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_itables(rate_policy="debounce", rate_delay=1)
        def table():
            return ITable(countries, select=True)

    with ui.card():
        ui.card_header("Fires per click")
        accessor_count = reactive.value(0)
        read_count = reactive.value(0)

        @reactive.effect
        def _count_accessor():
            table.selected()
            with reactive.isolate():
                accessor_count.set(accessor_count() + 1)

        @reactive.effect
        def _count_reactive_read():
            req(table.widget)
            reactive_read(table.widget, "selected_rows")
            with reactive.isolate():
                read_count.set(read_count() + 1)

        @render.code
        def counts():
            return (
                f"table.selected(): {accessor_count()}\n"
                f"reactive_read() debounced 1s: {read_count()}"
            )

A burst of clicks: the accessor-driven counter climbs with every click, while the debounced reactive_read() counter is still waiting out the window; once the window elapses, it catches up in a single step:

.read()

table.read("selected_rows") (or reactive_read(table.widget, "selected_rows")) returns the same value as table.selected(), but follows the rate policy above instead of firing on every click. Nothing else on an ITable is worth reading reactively.

Large data

The whole table is sent to the browser up front. Past maxBytes (64 KB by default), ITables downsamples and says so in the info line; maxBytes=0 sends everything, but tens of thousands of rows take seconds to appear. For more rows, use Shiny’s render.DataGrid/render.DataTable, which draw only the visible rows, or ipydatagrid’s StreamingDataGrid. See Large data & performance for the general approaches.

Layout and sizing

  • In a filling layout (the default), the table fills its container: the search box, filters, and footer stay put while the rows scroll. This relies on scrollY="100%", the default unless you set scrollY yourself.
  • height= on @render_itables (or output_widget(..., height=...)) sets a fixed height instead. Give it at least 350px; below that, the controls leave little room for rows. buttons and column_filters="header" each take another row of that height.
  • In a full_screen=True card, the table fills the expanded card.
  • Dark mode follows ui.input_dark_mode().

ITables vs. render.data_frame

Both render a data frame as an interactive table; the difference is in what the table is for.

ITables (@render_itables) Shiny render.DataGrid / render.DataTable
Scale Whole frame shipped to the browser; downsamples past ~64KB by default Virtualized: renders only visible rows, handles 100k+ rows smoothly
Selection Row(s), via click/Ctrl/Shift Row, column, cell, or rectangular region
Editing No editable=True, cell-level
Search Global search box + optional per-column filters/SearchPanes, built in filters=True for per-column text filters; no global search box
Styling DataTables columnDefs/CSS (JS), or a rendered pandas Styler Python styles= callable – no JS required
Export buttons=[...] (copy, CSV, Excel, print) built in None built in
Extras SearchPanes, RowGroup, FixedColumns, and the rest of the DataTables extension catalog None of that catalog; zero extra JS dependency
Dark mode Follows ui.input_dark_mode() Native (it’s a Shiny/bslib component)

Choose ITables when you want the DataTables feature set – global search, export buttons, SearchPanes, a Jupyter-familiar look – and your data comfortably fits in the browser. Choose render.DataGrid/DataTable for large data, cell editing, or finer-grained selection, with no extra dependency.

Learn more

  • itables.org – the full options reference, including every DataTables extension itables bundles (SearchPanes, SearchBuilder, RowGroup, FixedColumns, KeyTable, and more).
  • itables.org: Shiny – upstream’s own Shiny notes.
  • DataTables – the underlying jQuery table library, for option names and extension docs that itables passes through.
  • ipydatagrid: cell-block selection, in-cell bars, and editable cells.
  • reactable: a lighter, theming-focused table.
  • perspective: pivot-style exploration over very large data.