Skip to content

Table

The Table element displays tabular data with rich features like sorting, filtering, searching, and row actions.

Table Class

Table

Table(content: Union[DataFrame, Dataset, Workbook], downloadable: bool = False, title: str = '', description: str = '', show_title: bool = True, show_description: bool = True, cell_colors: Optional[DataFrame] = None, text_colors: Optional[DataFrame] = None, column_descriptions: Optional[Dict[str, str]] = None, searchable: bool = True, missing_values: bool = False, notes: Optional[List[str]] = None, links: Optional[List[str]] = None, show_filter: bool = False, max_table_rows_to_display: int = 2500, xlsx_config: Dict | None = None, editable: bool = True, max_table_row_height: Optional[int] = None, markdown_columns: Optional[Union[List[str], bool]] = None, missing_value_text: str | None = None, editable_columns: Optional[Union[List[str], bool]] = True, row_actions: Optional[List[PageUpdateCallback]] = None, selectable: bool = False, selected_rows: Optional[List[int]] = None, selection_type: TableSelectionType = TableSelectionType.INCLUDE, non_selectable_rows: Optional[List[int]] = None, column_formatters: Optional[Dict[str, str]] = None, on_edit_update: Optional[PageUpdateCallback] = None, on_row_select: Optional[PageUpdateCallback] = None, data_grid_features: DataGridFeatures | None = None, reference_id: Optional[str] = '', info_content: Optional[str] = None, column_info_content: Optional[Dict[str, str]] = None, persist_as_json: bool = False, lightweight: bool = False, **kwargs)

A Table element.

Parameters:

  • content (Union[DataFrame, Dataset, Workbook]) –

    A DataFrame, Pandas series, or Dataset. Dataframes that have column with the reserved keyword id as their name are not supported and will raise an Exception.

  • downloadable (bool, default: False ) –

    Whether this table should be downloaded, defaults to False.

  • title (str, default: '' ) –

    The title of the element, defaults to ''.

  • description (str, default: '' ) –

    The element's description, defaults to ''.

  • show_title (bool, default: True ) –

    Whether to show the title on the page when rendered, defaults to True.

  • show_description (bool, default: True ) –

    Whether to show the description to the page when rendered, defaults to True.

  • cell_colors (Optional[DataFrame], default: None ) –

    Dataframe of cell colors as hex strings. Columns should exist inside source dataset, defaults to None, joined to in content dataframe by index. See code example below for usage.

  • text_colors (Optional[DataFrame], default: None ) –

    Dataframe of text colors as hex strings. Columns should exist inside source dataset, defaults to None, joined to in content dataframe by index. See code example below for usage.

  • column_descriptions (Optional[Dict[str, str]], default: None ) –

    Dictionary {column_name: column_description} of column descriptions, defaults to None. Presented to user as tooltips and can be fed to agents as additional context

  • searchable (bool, default: True ) –

    Toggles the ability to search table values, defaults to True.

  • missing_values (bool, default: False ) –

    Set to true if this table contains missing values and you want to flag this to the user.

  • notes (Optional[List[str]], default: None ) –

    The popover description that shows upon hovering over a particular row. Each index in the list maps to the corresponding row. Defaults to None.

  • links (Optional[List[str]], default: None ) –

    The link to redirect to when hovering over a particular row. Each index in the list maps to the corresponding row. Defaults to None.

  • show_filter (bool, default: False ) –

    Whether to show the filter on the page when rendered, defaults to False.

  • max_table_rows_to_display (int, default: 2500 ) –

    Defaults to 2500 rows, this is the number of rows that will be sent to the frontend, however the entire table is downloadable from the frontend regardless of this limit. Browsers with more resources may be able to handle much larger limits than this default value.

  • xlsx_config (Dict | None, default: None ) –

    dictionary of configurable parameters for tables that are backed by an xlsx object

  • editable (bool, default: True ) –

    should this table be editable by the user from the frontend. This defaults to true.

  • max_table_row_height (Optional[int], default: None ) –

    Maximum characters before truncating cell text with "view more/less" link. When set, enables auto row height and disables density control. Defaults to None (ellipsis truncation, density enabled).

  • markdown_columns (Optional[Union[List[str], bool]], default: None ) –

    Controls which columns render their content as markdown. If None or an empty list ([]), no columns will render as markdown. If set to True, all columns will render as markdown. If set to a list of column names, only the specified columns will render as markdown, while others will render as plain text

  • missing_value_text (str | None, default: None ) –

    A string used to replace missing values (e.g., None, NaN, or NaT) in the table when rendered. Defaults to None, meaning missing values will remain as-is.

  • editable_columns (Optional[Union[List[str], bool]], default: True ) –

    Controls which columns are editable. If None, False, or an empty list ([]), no columns will be editable. If set to True, all columns will be editable. If set to a list of column names, only the specified columns will be editable. Defaults to True. You must turn this to False if editable is also False if you wish to disable table edits.

  • row_actions (Optional[List[PageUpdateCallback]], default: None ) –

    A list of row_action_callbacks that will be attached to the first rows of the table, as determined by the max_table_rows_to_display parameter. Defaults to None.

  • selectable (bool, default: False ) –

    Enable row selection checkboxes without requiring row_actions. When True, users can select rows and the selections are synced to the backend. Use get_selected_data() to get a DataFrame of selected rows. Defaults to False.

  • selected_rows (Optional[List[int]], default: None ) –

    List of row indices to select by default. Used with selection_type to specify which rows are initially selected. Defaults to None (no default selection).

  • selection_type (TableSelectionType, default: INCLUDE ) –

    The selection mode. Use TableSelectionType.INCLUDE to select the rows in selected_rows, or TableSelectionType.EXCLUDE to select all rows EXCEPT those in selected_rows. Defaults to TableSelectionType.INCLUDE.

  • column_formatters (Optional[Dict[str, str]], default: None ) –

    A dictionary of key: Column Name and value: Python format string, that optionally formats the specified numeric columns on the frontend. As an example, '{total_spending: "$ {:,.2f}"}' would format the total_spending column as currency, while sorting as an float. Defaults to None.

  • data_grid_features (DataGridFeatures | None, default: None ) –

    MUI DataGrid style and organization options.

  • on_edit_update (Optional[PageUpdateCallback], default: None ) –

    Page update callback. Allows execution of a function after the table's contents get saved after an edit. Must be decorated using the @page_update_callback decorator. Takes a StoreInterface and optionally client runners as arguments, defaults to None.

  • on_row_select (Optional[PageUpdateCallback], default: None ) –

    Page update callback. Allows execution of a function when row selection changes. Must be decorated using the @page_update_callback decorator. Only triggered when selectable=True. Defaults to None.

  • non_selectable_rows (Optional[List[int]], default: None ) –

    List of row indices that cannot be selected by the user. Checkboxes for these rows are rendered as disabled. Has no effect when selectable=False and no row_actions are configured. Defaults to None (all rows selectable).

  • reference_id (Optional[str], default: '' ) –

    A user-defined reference ID for the unique identification of Table element within the Page, defaults to ''.

  • info_content (Optional[str], default: None ) –

    Description to be displayed within the element's info button. Use RichText/Markdown for advanced formatting.

  • column_info_content (Optional[Dict[str, str]], default: None ) –

    Dictionary mapping column names to info text displayed in column header tooltips. Defaults to None.

  • persist_as_json (bool, default: False ) –

    If True, stores table data as pre-serialized JSON instead of using S3 persistence. This optimization reduces page size and improves performance, but has limitations: - Cannot access or modify the underlying DataFrame after initial creation - Row selection (selectable, on_row_select) is not supported - Table editing (editable, editable_columns, on_edit_update) is not supported Best used for static, display-only tables with many button columns where callback deduplication and JSON storage provide significant performance benefits. Defaults to False.

  • lightweight (bool, default: False ) –

    If True, renders the table with the lightweight renderer, which uses a clean data contract (primitive cell values plus a sparse styling map) for a smaller payload and lazy-loaded bundle. Well-suited to display/edit tables and to tables shown in Iris. It intentionally omits some heavier features of the default renderer (for example validation rules, subtables, per-column info popovers, and dynamic getCellColors functions); use the default renderer when those are required. Defaults to False.

Raises:

  • NotImplementedError

    EXAMPLE:

    # Imports from virtualitics_sdk import Table, PREDICT_ERROR_TEXT_COLOR...
    ...
    # Example usage class ExampleStep(Step): def run(self, flow_metadata):...
    point_per_cluster = 5 # Number of rows we want cell/text color to apply to cell_colors = pandas.DataFrame({"Y Feature": ["#39cd63"] * point_per_cluster}) text_colors = pandas.DataFrame({"X Feature": ["#ee2310"] * point_per_cluster}) table = Table(example_dataset, title="Example Table", description="This is a table showing cells/text color", downloadable=True, cell_colors=cell_colors, text_colors=text_colors)  from sklearn.datasets import load_iris  from virtualitics_sdk.elements.table import Table, DataGridFeatures, ColumnGroup, ColumnField, GridColumn  iris = load_iris(as_frame=True) columns = [ GridColumn(field="sepal_length", header_name="sepal length (cm)", dtype="number"), GridColumn(field="sepal_width", header_name="sepal width (cm)", dtype="number", col_spanning=True), GridColumn(field="sepal_width_2", header_name="sepal width (cm)", dtype="number", col_spanning=True), GridColumn(field="petal_length", header_name="petal length (cm)", dtype="number"), GridColumn(field="petal_width", header_name="petal width (cm)", dtype="number"), GridColumn(field="target", header_name="target", dtype="text"), ] iris.frame.columns = ["sepal_length", "sepal_width", "petal_length", "petal_width", "target"] column_grouping = [ ColumnGroup( group_id="flower measurements", children=[ ColumnGroup( group_id="sepal", children=[ColumnField(field="sepal_length"), ColumnField(field="sepal_width"), ColumnField(field="sepal_width_2")], ), ColumnGroup( group_id="petal", children=[ColumnField(field="petal_length"), ColumnField(field="petal_width")], ) ], ), ColumnGroup(group_id="classification", children=[ColumnField(field="target")]), ]  data_grid_features = DataGridFeatures(columns=columns, column_grouping_model=column_grouping) df['sepal_width_2'] = df.sepal_width table_with_grouping_and_spanning = Table(df, title="Iris Dataset with Grouping and Spanning", data_grid_features=data_grid_features)  The above Table examples will be displayed as:  . image:: ../images/table_color_ex.png :align: center

Basic Usage

from virtualitics_sdk import Table
import pandas as pd

# Create a DataFrame
data = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'San Francisco', 'Boston']
})

# Create a table
table = Table(
    id="my_table",
    data=data,
    title="Employee Data"
)

Advanced Features

Column Configuration

Customize column display and behavior:

from virtualitics_sdk.elements.table import GridColumn

columns = [
    GridColumn(
        field="name",
        header_name="Full Name",
        width=200,
        editable=False
    ),
    GridColumn(
        field="salary",
        header_name="Salary",
        width=150,
        type="number",
        editable=True
    )
]

table = Table(
    id="employees",
    data=df,
    columns=columns
)

Column Grouping

Group related columns:

from virtualitics_sdk.elements.table import ColumnGroup, ColumnField

column_grouping = [
    ColumnGroup(
        group_id="personal",
        children=[
            ColumnField(field="firstName"),
            ColumnField(field="lastName"),
            ColumnField(field="age")
        ]
    ),
    ColumnGroup(
        group_id="contact",
        children=[
            ColumnField(field="email"),
            ColumnField(field="phone")
        ]
    )
]

table = Table(
    id="contacts",
    data=df,
    column_grouping=column_grouping
)

Row Actions

Add custom actions for each row:

from virtualitics_sdk.elements.table import RowAction, RowActionType

class ViewDetailsAction(RowAction):
    def __init__(self):
        super().__init__(
            title="View Details",
            description="View full details for this row",
            type=RowActionType.REDIRECT
        )

table = Table(
    id="data_table",
    data=df,
    row_actions=[ViewDetailsAction()]
)

# In your action() method, handle the action
def action(self, flow_metadata):
    table = self.page.get_element_by_id("data_table")
    selected_rows = table.get_selected_rows()

    # Process selected rows
    for row in selected_rows:
        process_row(row)

Cell Styling

Apply conditional formatting:

# Define styling rules
def style_cells(df):
    # Add color based on values
    styled_df = df.copy()

    # Color cells based on conditions
    for idx, row in styled_df.iterrows():
        if row['status'] == 'Complete':
            # Green background
            styled_df.at[idx, 'status_color'] = '#DFF7F1'
        elif row['status'] == 'Error':
            # Red background
            styled_df.at[idx, 'status_color'] = '#FDE7E7'

    return styled_df

table = Table(
    id="status_table",
    data=style_cells(df)
)

Enable Editing

Allow users to edit cell values:

table = Table(
    id="editable_table",
    data=df,
    editable=True,
    on_cell_edit=handle_edit  # Callback function
)

def handle_edit(row_id, column, new_value):
    # Handle the edit
    print(f"Row {row_id}, Column {column} changed to {new_value}")

Selection Modes

Control row selection:

# Single row selection
table = Table(
    id="single_select",
    data=df,
    selection_mode="single"
)

# Multiple row selection
table = Table(
    id="multi_select",
    data=df,
    selection_mode="multiple",
    checkbox_selection=True
)

# Get selected rows in action()
def action(self, flow_metadata):
    table = self.page.get_element_by_id("multi_select")
    selected = table.get_selected_rows()
    # selected is a list of row dictionaries

Pagination

Control pagination settings:

table = Table(
    id="paginated_table",
    data=large_df,
    page_size=25,  # Rows per page
    pagination=True
)

Filtering and Sorting

Enable column filters and sorting:

table = Table(
    id="filterable_table",
    data=df,
    enable_filter=True,  # Column filters
    enable_sort=True,    # Column sorting
    enable_search=True   # Global search
)

Exporting Data

Allow users to export table data:

table = Table(
    id="exportable_table",
    data=df,
    enable_export=True,  # Enable export button
    export_formats=["csv", "xlsx", "json"]
)

Performance Optimization

For large datasets:

# Use server-side operations
table = Table(
    id="large_table",
    data=df,
    pagination=True,
    page_size=50,
    server_side_pagination=True,  # Load data as needed
    virtual_scrolling=True        # Render only visible rows
)

Persist tables between steps:

# In step 1 - create and store
def run(self, flow_metadata):
    table = Table(id="results", data=df)
    self._outLink.results_table = table

# In step 2 - retrieve and use
def run(self, flow_metadata):
    previous_table = self._inLink.results_table
    data = previous_table.data  # Get the DataFrame

GridColumn

Equivalent to a MUI GridColDef

https://mui.com/x/react-data-grid/column-definition/

ColumnGroup

column_grouping = [
ColumnGroup(
    group_id="internal data",
    children=[ColumnField(field="id")]
),
ColumnGroup(
    group_id="character",
    children=[
        ColumnGroup(
            group_id="naming",
            children=[
                ColumnField(field="lastName"),
                ColumnField(field="firstName")
            ]
        ),
        ColumnField(field="age")
    ]
)

]

RowAction Types

Best Practices

  • Column Width: Set appropriate widths for readability
  • Pagination: Use pagination for tables with >100 rows
  • Unique IDs: Ensure DataFrame has unique row identifiers
  • Data Types: Use proper pandas dtypes for correct sorting
  • Performance: Consider server-side operations for large datasets
  • Export: Enable export for data users may need externally

See Also