### Install JavaScript Dependencies and Run Dev Server Source: https://github.com/mwouts/itables/blob/main/packages/itables_anywidget/README.md Commands to install JavaScript dependencies and start the development server for itables_anywidget. ```sh npm install npm run dev ``` -------------------------------- ### Development Installation Source: https://github.com/mwouts/itables/blob/main/packages/itables_anywidget/README.md Steps for setting up a virtual environment and installing itables_anywidget in editable mode with development dependencies. ```sh python -m venv .venv source .venv/bin/activate pip install -e ".[dev]" ``` -------------------------------- ### Install ITables with DT Requirements Source: https://github.com/mwouts/itables/blob/main/apps/shiny/README.md Install the necessary Python packages for the ITables with DT example. Ensure you have Python and pip installed. ```bash pip install -r itables_DT/requirements.txt ``` -------------------------------- ### Install itables_anywidget Source: https://github.com/mwouts/itables/blob/main/packages/itables_anywidget/README.md Use this command to install the itables_anywidget package. ```sh pip install itables_anywidget ``` -------------------------------- ### Install ITables Requirements Source: https://github.com/mwouts/itables/blob/main/apps/shiny/README.md Install the necessary Python packages for the ITables widget example. Ensure you have Python and pip installed. ```bash pip install -r itable_widget/requirements.txt ``` -------------------------------- ### Install Dependencies and Build JS Bundle Source: https://github.com/mwouts/itables/blob/main/packages/dt_for_itables/README.md Run these commands to install project dependencies and then build the JavaScript bundle for ITables. ```bash npm install npm run build:js ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/mwouts/itables/blob/main/docs/developing.md Install the pre-commit hooks to ensure code quality and consistency before committing changes. ```shell pre-commit install ``` -------------------------------- ### Install ITables with Pip Source: https://github.com/mwouts/itables/blob/main/README.md Use this command to install the itables package using pip. ```shell pip install itables ``` -------------------------------- ### Initialize itables and load sample data Source: https://github.com/mwouts/itables/blob/main/docs/options/column_control.md Initializes the itables library for notebook usage and loads a sample DataFrame. This is a prerequisite for most itables examples. ```python import itables itables.init_notebook_mode() df = itables.sample_dfs.get_countries() ``` -------------------------------- ### ITables TOML Configuration Example Source: https://context7.com/mwouts/itables/llms.txt Example of an `itables.toml` file for configuring table appearance, export buttons, and column control extensions. Place this file in your project root or config directory. ```toml # itables.toml — place in your project root or home config dir # Less compact look classes = ["display", "nowrap"] # Always show export buttons buttons = ["pageLength", "copyHtml5", "csvHtml5", "excelHtml5"] # Column control extension (ITables >= 2.5) [[columnControl]] target = 0 content = ["order"] [[columnControl]] target = "tfoot" content = ["search"] [ordering] indicators = false handler = false ``` -------------------------------- ### Build ITables Documentation Locally Source: https://github.com/mwouts/itables/blob/main/docs/developing.md Build the Jupyter Book documentation for ITables locally. This command requires the 'itables' kernel to be installed. ```shell pixi run -e docs jupyter book build docs ``` -------------------------------- ### Initialize itables for Jupyter Source: https://github.com/mwouts/itables/blob/main/docs/pandas_dataframes.md Import necessary libraries and initialize itables for notebook mode. This setup is required before displaying DataFrames. ```python import pandas as pd import itables dict_of_test_dfs = itables.sample_pandas_dfs.get_dict_of_test_dfs() itables.init_notebook_mode() ``` -------------------------------- ### Install ITables with Conda Source: https://github.com/mwouts/itables/blob/main/README.md Use this command to install the itables package using conda. ```shell conda install itables -c conda-forge ``` -------------------------------- ### Import itables and get sample data Source: https://github.com/mwouts/itables/blob/main/docs/custom_extensions.md Imports the itables library and retrieves a sample DataFrame. This is a prerequisite for displaying tables. ```python import itables df = itables.sample_dfs.get_countries() ``` -------------------------------- ### Install Development Version of ITables in Colab Source: https://github.com/mwouts/itables/blob/main/docs/developing.md Install the development version of ITables from GitHub into an online environment like Google Colab. This is useful for testing JavaScript/HTML changes. ```shell !pip uninstall itables -y !pip install git+https://github.com/mwouts/itables.git@branch ``` -------------------------------- ### Start Jupyter Lab in Pixi Environment Source: https://github.com/mwouts/itables/blob/main/docs/developing.md Launch Jupyter Lab within the pixi development environment. This allows for interactive testing of ITables in a notebook context. ```shell pixi run jupyter lab ``` ```shell jupyter lab ``` -------------------------------- ### itables Configuration for Column Controls Source: https://github.com/mwouts/itables/blob/main/docs/options/column_control.md Provides an example of how to configure column controls and ordering globally using the itables.toml configuration file. This allows for persistent settings across sessions. ```toml [[columnControl]] target = 0 content = ["order"] [[columnControl]] target = "tfoot" content = ["search"] [ordering] indicators = false handler = false ``` -------------------------------- ### Custom DataTables bundle setup (index.js) Source: https://github.com/mwouts/itables/blob/main/docs/custom_extensions.md Configures a custom DataTables bundle by importing necessary components and extensions. This file is used to build the bundle. ```javascript import JSZip from 'jszip'; import jQuery from 'jquery'; import pdfMake from 'pdfmake'; import DataTable from 'datatables.net-dt'; import 'datatables.net-dt/css/dataTables.dataTables.min.css'; import 'datatables.net-buttons-dt'; import 'datatables.net-buttons/js/buttons.html5.mjs'; import 'datatables.net-buttons/js/buttons.print.mjs'; import 'datatables.net-buttons-dt/css/buttons.dataTables.min.css'; DataTable.Buttons.jszip(JSZip); DataTable.Buttons.pdfMake(pdfMake); pdfMake.vfs = pdfFonts.pdfMake.vfs; export { DataTable, jQuery }; ``` -------------------------------- ### Build custom DataTables bundle Source: https://github.com/mwouts/itables/blob/main/docs/custom_extensions.md Commands to install dependencies and build the custom DataTables bundle. Run these after modifying package.json and src/index.js. ```bash # Install the dependencies in package.json npm install # Install the additional dependencies npm install pdfmake --save # Create dt_bundle.js and dt_bundle.css npm run build ``` -------------------------------- ### Activate ITables Development Environment Source: https://github.com/mwouts/itables/blob/main/docs/developing.md Use this command to activate the development environment managed by pixi. Ensure pixi is installed first. ```shell pixi shell ``` -------------------------------- ### Initialize itables for Polars DataFrames Source: https://github.com/mwouts/itables/blob/main/docs/polars_dataframes.md Imports necessary libraries and initializes itables for notebook use. This setup is required before displaying any Polars DataFrames. ```python import polars as pl import itables dict_of_test_dfs = itables.sample_polars_dfs.get_dict_of_test_dfs() itables.init_notebook_mode() ``` -------------------------------- ### Install ITables Kernel for Jupyter Source: https://github.com/mwouts/itables/blob/main/docs/developing.md Create a dedicated Jupyter kernel named 'itables' for testing documentation locally. This is required before building the documentation. ```python python -m ipykernel install --name itables --user ``` -------------------------------- ### Check ITables Version Source: https://github.com/mwouts/itables/blob/main/docs/troubleshooting.md Retrieve the currently installed version of the ITables library. ```python import itables itables.__version__ ``` -------------------------------- ### ITables in Shiny for Python Source: https://context7.com/mwouts/itables/llms.txt Uses the ITable widget via shinywidgets for reactive Shiny applications. Access selected_rows through reactive_read. Install with 'pip install itables[shiny]'. ```python # Shiny Express syntax from shiny.express import input, render, ui from shinywidgets import output_widget, render_widget, reactive_read from itables.widget import ITable from itables.sample_dfs import get_dict_of_test_dfs import pandas as pd dfs = get_dict_of_test_dfs() u.input_select("table_name", "Table:", choices=list(dfs.keys())) @render_widget def my_table(): return ITable(dfs[input.table_name()], select=True, caption="Interactive Table") @render.code def selected(): return str(reactive_read(my_table.widget, "selected_rows")) ``` -------------------------------- ### itables.streamlit.interactive_table Source: https://context7.com/mwouts/itables/llms.txt Renders a DataFrame as an interactive DataTable in Streamlit. Returns a dict with 'selected_rows' when select=True. Install with 'pip install itables[streamlit]'. ```python import streamlit as st import pandas as pd from itables.streamlit import interactive_table df = pd.DataFrame({ "city": ["Paris", "Berlin", "Tokyo", "New York"], "country": ["France", "Germany", "Japan", "USA"], "pop_M": [2.1, 3.6, 13.9, 8.3], }) st.title("ITables in Streamlit") # Basic display interactive_table(df, caption="World Cities") # With row selection and export buttons result = interactive_table( df, key="my_table", caption="Selectable Cities", select=True, selected_rows=[0, 2], buttons=["copyHtml5", "csvHtml5", "excelHtml5"], classes=["display", "nowrap", "stripe"], ) st.write("Selected rows:", result.get("selected_rows", [])) # → Selected rows: [0, 2] (updates live when user clicks rows) ``` -------------------------------- ### Using JavascriptFunction for Callbacks Source: https://context7.com/mwouts/itables/llms.txt Utilize `JavascriptFunction` for JavaScript callbacks like `createdCell` or `initComplete`. This example colors negative deltas red and logs a message when the table is ready. ```python import pandas as pd import itables from itables import JavascriptFunction, JavascriptCode itables.init_notebook_mode() df = pd.DataFrame({ "item": ["Widget A", "Widget B", "Widget C"], "price": [1234567.89, 9876543.21, 555555.55], "delta": [-100.5, 200.0, -50.25], }) # JavascriptFunction: color negative deltas red itables.show( df, columnDefs=[ { "targets": [2], "createdCell": JavascriptFunction( "function(td, cellData, rowData, row, col) { const raw = this.api().cell(row, col).render('sort'); if (raw < 0) { $(td).css('color', 'red'); } }" ), } ], ) # JavascriptFunction: custom initComplete callback itables.show( df, initComplete=JavascriptFunction( "function(settings, json) { console.log('Table ready', settings.nTable.id); }" ), ) ``` -------------------------------- ### Configure 'colvis' Button with Collection Layout Source: https://github.com/mwouts/itables/blob/main/docs/options/colvis.md Demonstrates how to configure the 'colvis' button with a 'collectionLayout' and 'popoverTitle' in Python, mirroring a JavaScript example. This allows for more advanced customization of the column visibility control. ```javascript buttons: [ { extend: 'colvis', collectionLayout: 'fixed columns', popoverTitle: 'Column visibility control' } ] ``` ```python buttons = [ { "extend": "colvis", "collectionLayout": "fixed columns", "popoverTitle": "Column visibility control" } ] ``` -------------------------------- ### Display Images and Links in ITables Source: https://github.com/mwouts/itables/blob/main/docs/options/allow_html.md Shows how to embed images and create clickable links within an ITables DataFrame by utilizing HTML tags and setting `allow_html=True`. This example populates country, capital, and flag columns with HTML. ```python df = itables.sample_dfs.get_countries() df["flag"] = [ '' ''.format(code=code.lower(), country=country) for code, country in zip(df.index, df["country"]) ] df["country"] = [ '{}'.format(country, country) for country in df["country"] ] df["capital"] = [ '{}'.format(capital, capital) for capital in df["capital"] ] itables.show(df, allow_html=True) ``` -------------------------------- ### Override ITables Options for a Single Call Source: https://context7.com/mwouts/itables/llms.txt Use `itables.show()` with specific arguments to override global configuration for a single table display. For example, `maxBytes=0` removes the size limit. ```python import itables.sample_dfs as sdf itables.show(sdf.get_countries(), maxBytes=0) ``` -------------------------------- ### Enable Row Selection with Pre-selected Rows Source: https://github.com/mwouts/itables/blob/main/docs/options/select.md Enables row selection in the table and pre-selects specific rows using the `selected_rows` argument. This example also includes buttons for exporting data, which will only export the selected rows. ```python import itables itables.init_notebook_mode() itables.show( itables.sample_dfs.get_countries(), select=True, selected_rows=[2, 4, 5], buttons=["copyHtml5", "csvHtml5", "excelHtml5"], ) ``` -------------------------------- ### Column Controls in Table Footer - itables Source: https://github.com/mwouts/itables/blob/main/docs/options/column_control.md Illustrates placing column controls, such as search, within the table's footer using the 'target' option. This example also shows targeting specific columns by index. ```python itables.show( df, columnControl=[ {"target": 0, "content": ["order"]}, {"target": "tfoot", "content": ["search"]}, ], ordering={"indicators": False, "handler": False}, ) ``` -------------------------------- ### Set Max Bytes for Downsampling Source: https://github.com/mwouts/itables/blob/main/docs/downsampling.md Configures the maximum number of bytes allowed for table data before downsampling is applied. This example sets the limit to 8KB and then checks the downsampling status and actual bytes of a sample DataFrame. ```python itables.options.maxBytes = "8KB" df = itables.sample_dfs.get_countries() itables.downsample.as_nbytes(itables.options.maxBytes), itables.downsample.nbytes(df) ``` -------------------------------- ### Initialize iTables and Load Sample Data Source: https://github.com/mwouts/itables/blob/main/docs/options/layout.md Initializes iTables for notebook use and loads a sample DataFrame. This is a prerequisite for displaying tables. ```python import itables itables.init_notebook_mode() df = itables.sample_dfs.get_countries() ``` -------------------------------- ### Initialize ITables and Enable HTML Source: https://github.com/mwouts/itables/blob/main/docs/pandas_style.md Initializes ITables for notebook mode and enables HTML rendering. Ensure you trust the content before enabling `allow_html`. ```python import numpy as np import pandas as pd import itables itables.init_notebook_mode() # Before you do this, make sure that you trust the content of your tables itables.options.allow_html = True ``` -------------------------------- ### Package and Publish New Version Source: https://github.com/mwouts/itables/blob/main/packages/dt_for_itables/README.md Commands to package the extension and publish it to npm. Ensure you have logged in and updated the version in package.json. ```bash # Package the extension npm pack # Publish the package on npm with npm login npm publish --access public ``` -------------------------------- ### ITable Widget for Jupyter Source: https://context7.com/mwouts/itables/llms.txt Renders a DataFrame as an interactive DataTable in Jupyter. Supports row selection, data updates, and programmatic control. Install with 'pip install itables[widget]'. ```python from itables.widget import ITable import pandas as pd df = pd.DataFrame({ "name": ["Alice", "Bob", "Carol", "Dave"], "score": [92, 85, 78, 95], }) # Create widget with row selection enabled table = ITable(df, select=True, selected_rows=[0, 2], caption="Scores") table # display in notebook # Read back which rows the user selected print(table.selected_rows) # e.g. [0, 2] # Update the selection programmatically table.selected_rows = [1, 3] # Update the underlying data table.df = df.head(3) # Update data and selection atomically (avoids IndexError on mismatch) table.update(df, selected_rows=[0]) # Update caption, style, classes without re-creating the widget table.caption = "Updated caption" table.style = "width:80%;margin:auto" table.classes = "display cell-border" # Access selected rows as a sub-DataFrame print(table.df.iloc[table.selected_rows]) ``` -------------------------------- ### ITable Dash Component Source: https://context7.com/mwouts/itables/llms.txt Embeds an interactive DataTable in a Plotly Dash application. Accepts same options as show(). Use ITableOutputs and updated_itable_outputs for reactive updates. Install with 'pip install itables[dash]'. ```python from dash import Dash, Input, Output, State, callback, html from itables.dash import ITable, ITableOutputs, updated_itable_outputs from itables.sample_dfs import get_countries import pandas as pd app = Dash(__name__) df = get_countries() app.layout = html.Div([ html.H1("ITables Dash Demo"), # Display-only table ITable( id="my_table", df=df, caption="World Countries", select=True, buttons=["copyHtml5", "csvHtml5"], ), html.Div(id="selection_output"), ]) # Read selected rows @callback( Output("selection_output", "children"), Input("my_table", "selected_rows"), ) def show_selection(selected_rows): return f"Selected rows: {selected_rows}" # Reactively update the entire table (data + selection + options) @callback( ITableOutputs("my_table"), Input("some_input", "value"), State("my_table", "selected_rows"), State("my_table", "dt_args"), ) def update_table(value, selected_rows, dt_args): new_df = df[df["continent"] == value] if value else df return updated_itable_outputs( df=new_df, caption=f"Filtered: {value}", selected_rows=selected_rows, current_dt_args=dt_args, ) if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Initialize Notebook Mode for ITables Source: https://github.com/mwouts/itables/blob/main/docs/troubleshooting.md Ensure `init_notebook_mode` is called to enable interactive tables. If `connected=True` is used, an internet connection is required. ```python import pandas as pd import itables df = pd.DataFrame() itables.show(df, connected=False) ``` -------------------------------- ### Activate Cascade Filtering with SearchPanes Source: https://github.com/mwouts/itables/blob/main/docs/options/search_panes.md Demonstrates activating cascade filtering using `searchPanes.cascadePanes` and configuring the layout for Jupyter notebooks. The `columns` argument specifies which columns to enable search panes for. ```python import itables itables.init_notebook_mode() df = itables.sample_pandas_dfs.get_countries(climate_zone=True) itables.show( df.reset_index(), layout={"top1": "searchPanes"}, searchPanes={"layout": "columns-3", "cascadePanes": True, "columns": [1, 6, 7]}, ) ``` -------------------------------- ### Show ITables Configuration Source: https://github.com/mwouts/itables/blob/main/docs/configuration.md Run this command in your terminal to display the path to the currently used ITables configuration file. ```bash python -m itables.show_config ``` -------------------------------- ### Initialize SearchBuilder with Predefined Criteria Source: https://github.com/mwouts/itables/blob/main/docs/options/search_builder.md Demonstrates how to initialize the SearchBuilder and set a predefined search criterion when displaying a DataFrame. This is useful for setting an initial filter state. ```python import itables itables.init_notebook_mode() df = itables.sample_dfs.get_countries(climate_zone=True) itables.show( df, layout={"top1": "searchBuilder"}, searchBuilder={ "preDefined": { "criteria": [ {"data": "climate_zone", "condition": "=", "value": ["Sub-tropical"]} ] } }, ) ``` -------------------------------- ### Initialize itables with JavaScript Source: https://github.com/mwouts/itables/blob/main/src/itables/html/datatables_template.html This snippet shows how to initialize itables on multiple tables on a page using their IDs. Ensure the itables library is loaded before executing this script. ```javascript import { ITable, jQuery as $ } from 'https://www.unpkg.com/dt_for_itables/dt_bundle.js'; document.querySelectorAll("#table_id:not(.dataTable)").forEach(table => { if (!(table instanceof HTMLTableElement)) return; let dt_args = {}; new ITable(table, dt_args); }); ``` -------------------------------- ### Import itables and Sample Data Functions Source: https://github.com/mwouts/itables/blob/main/tests/test_notebook.ipynb Import necessary functions from the itables library for notebook initialization and data retrieval. Ensure these imports are present before using the library's features. ```python from itables import init_notebook_mode from itables.sample_dfs import get_countries ``` -------------------------------- ### Set Row Order with 'order' Option Source: https://github.com/mwouts/itables/blob/main/docs/options/order.md Use the 'order' option to pre-select a specific sorting order for the datatable rows. This example sorts the 'a' column in ascending order. ```python import pandas as pd import itables itables.init_notebook_mode() sorted_df = pd.DataFrame({"a": [2, 1]}, index=pd.Index([1, 2], name="i")) itables.show(sorted_df, order=[[1, "asc"]]) ``` -------------------------------- ### Initialize ITables with Custom Arguments Source: https://github.com/mwouts/itables/blob/main/tests/data/test_to_html_datatable/countries.html This snippet demonstrates how to initialize an ITables instance with custom arguments, including column definitions, data, and table layout. It's useful for advanced table configurations. ```javascript import { ITable, jQuery as $ } from 'https://www.unpkg.com/dt_for_itables@{dt_for_itables_version}/dt_bundle.js'; document.querySelectorAll("#table_id:not(.dataTable)").forEach(table => { if (!(table instanceof HTMLTableElement)) return; let dt_args = { "classes": ["display", "nowrap", "compact"], "columnDefs": [{"render": "function (data, type, row, meta) { return type === 'sort' || type === 'type' ? data[1] : data[0]; }", "targets": [4, 5] }], "data_json": "[[\"AW\", \"Latin America & Caribbean \", \"Aruba\", \"Oranjestad\", [-70.0167, -70.0167], [\"12.51670\", 12.5167]], [[ \"AF\", \"South Asia\", \"Afghanistan\", \"Kabul\", [\"69.1761\", 69.1761], [\"34.52280\", 34.5228]]], [[ \"AO\", \"Sub-Saharan Africa \", \"Angola\", \"Luanda\", [\"13.2420\", 13.242], [\"-8.81155\", -8.81155]]], [[ \"AL\", \"Europe & Central Asia\", \"Albania\", \"Tirane\", [\"19.8172\", 19.8172], [\"41.33170\", 41.3317]]], [[ \"AD\", \"Europe & Central Asia\", \"Andorra\", \"Andorra la Vella\", [\"1.5218\", 1.5218], [\"42.50750\", 42.5075]]]", "keys_to_be_evaluated": [["columnDefs", 0, "render"]], "layout": {"bottomEnd": null, "bottomStart": null, "topEnd": null, "topStart": null}, "order": [], "style": {"caption-side": "bottom", "margin": "auto", "table-layout": "auto", "width": "auto"}, "table_html": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
regioncountrycapitallongitudelatitude
code
", "text_in_header_can_be_selected": true }; new ITable(table, dt_args); }); ``` -------------------------------- ### Retrieve Selected Rows from ITable Source: https://github.com/mwouts/itables/blob/main/docs/apps/widget.md Access the `selected_rows` attribute to get a list of currently selected row indices in the ITable widget. Ensure `select=True` was passed during initialization. ```python table.selected_rows ``` -------------------------------- ### Enable KeyTable Navigation in itables Source: https://github.com/mwouts/itables/blob/main/docs/options/keys.md Use `itables.show` with `keys=True` to enable arrow key navigation for a specific table. Requires `itables.init_notebook_mode()` to be called first. ```python import itables itables.init_notebook_mode() itables.show( itables.sample_dfs.get_countries(), keys=True, ) ``` -------------------------------- ### Apply Background Gradient Styling Source: https://github.com/mwouts/itables/blob/main/docs/pandas_style.md Applies a background gradient to the DataFrame cells using a 'YlOrRd' colormap. This is a basic example of Pandas Styler's visual formatting capabilities. ```python s = df.style s.background_gradient(axis=None, cmap="YlOrRd") ``` -------------------------------- ### Initialize ITables Notebook Mode Source: https://github.com/mwouts/itables/blob/main/docs/formatting.md Initializes ITables for use in a notebook environment. This is a prerequisite for using ITables' display functions. ```python import itables itables.init_notebook_mode() ``` -------------------------------- ### Initialize ITable Widget Source: https://github.com/mwouts/itables/blob/main/docs/apps/widget.md Instantiate an ITable widget with a DataFrame and enable row selection. The df argument is optional for the ITable class. ```python from itables.sample_pandas_dfs import get_dict_of_test_dfs from itables.widget import ITable df = get_dict_of_test_dfs()["int_float_str"] table = ITable(df, selected_rows=[0, 2, 5], select=True) table ``` -------------------------------- ### Display Table with itables.show in Interactive Output Source: https://github.com/mwouts/itables/blob/main/docs/apps/widget.md Demonstrates using the `show` function within an `ipywidgets.interactive_output` to dynamically display different tables based on user selection from a dropdown. This approach is an alternative to the ITable widget for display-only purposes. ```python import ipywidgets as widgets from itables import show from itables.sample_dfs import get_dict_of_test_dfs def use_show_in_interactive_output(table_name: str): show( sample_dfs[table_name], caption=table_name, ) sample_dfs = get_dict_of_test_dfs() table_selector = widgets.Dropdown(options=sample_dfs.keys(), value="int_float_str") out = widgets.interactive_output( use_show_in_interactive_output, {"table_name": table_selector} ) widgets.VBox([table_selector, out]) ``` -------------------------------- ### Fixing Columns with itables Source: https://github.com/mwouts/itables/blob/main/docs/options/fixed_columns.md Use the `fixedColumns` option to specify the number of columns to fix at the start and end when scrolling horizontally. Ensure `scrollX` is set to `True` for horizontal scrolling to be enabled. ```python import string import numpy as np import pandas as pd import itables itables.init_notebook_mode() wide_df = pd.DataFrame( { letter: np.random.normal(size=100) for letter in string.ascii_lowercase + string.ascii_uppercase } ) itables.show( wide_df, fixedColumns={"start": 1, "end": 2}, scrollX=True, ) ``` -------------------------------- ### Initialize Notebook Mode for Connected Use Source: https://github.com/mwouts/itables/blob/main/docs/apps/notebook.md Activate ITables in a Jupyter environment while forcing it to load JavaScript libraries from the internet. This is useful for reducing notebook size or in environments like Google Colab. ```python itables.init_notebook_mode(connected=True) ``` -------------------------------- ### Set Global Max Bytes for Downsampling Source: https://github.com/mwouts/itables/blob/main/docs/downsampling.md Globally updates the `maxBytes` option for itables, affecting all subsequent DataFrame displays. This example sets the limit to 1MB, allowing larger DataFrames to be displayed without downsampling. ```python itables.options.maxBytes = "1MB" df ``` -------------------------------- ### Run ITables Widget App (Shiny Core) Source: https://github.com/mwouts/itables/blob/main/apps/shiny/README.md Launch the Shiny application using the ITables widget with Shiny Core. This command assumes you are in the project's root directory. ```bash shiny run itable_widget/app-core.py ``` -------------------------------- ### Test ITables Rendering in Notebook Source: https://github.com/mwouts/itables/blob/main/docs/developing.md This Python snippet initializes ITables for notebook use and displays a sample DataFrame. Test with both connected=False (default) and connected=True. ```python import itables # try both connected=False (the default) and connected=True itables.init_notebook_mode(connected=False) itables.sample_dfs.get_countries(html=True) ``` -------------------------------- ### itables.init_notebook_mode Source: https://context7.com/mwouts/itables/llms.txt Loads the DataTables JavaScript bundle and optionally patches _repr_html_ for automatic DataFrame display. It can be configured for all interactive display or selective use of `show()`. ```APIDOC ## itables.init_notebook_mode Loads the DataTables JavaScript bundle and optionally patches `_repr_html_` on all Pandas and Polars DataFrame/Series types so every DataFrame displays as an interactive table automatically. Pass `all_interactive=False` to keep automatic activation off and use `show` selectively. Pass `connected=False` for offline/air-gapped notebooks (keep the output cell!). ```python import itables # Auto-display ALL DataFrames as interactive tables (default) itables.init_notebook_mode() # Offline mode — embeds the DataTables bundle inside the notebook itables.init_notebook_mode(connected=False) # Only activate explicit show() calls, not automatic display itables.init_notebook_mode(all_interactive=False) import pandas as pd df = pd.DataFrame({"country": ["France", "Germany", "Japan"], "pop_M": [68, 84, 125]}) df # → displayed as interactive DataTable (because all_interactive=True) ``` ``` -------------------------------- ### Initialize itables Notebook Mode Source: https://github.com/mwouts/itables/blob/main/docs/options/show_index.md Initializes the itables library for use in a Jupyter Notebook environment. This is a prerequisite for using itables functionalities. ```python import pandas as pd import itables itables.init_notebook_mode() ``` -------------------------------- ### Initialize Notebook Mode Source: https://github.com/mwouts/itables/blob/main/docs/apps/notebook.md Activate ITables for all DataFrames in a Jupyter environment. This also enables offline mode by default. ```python import itables itables.init_notebook_mode() ``` -------------------------------- ### Render PyArrow Table with ITables Source: https://github.com/mwouts/itables/blob/main/docs/other_dataframes.md Use the `itables.show()` function to render a PyArrow Table. This allows for interactive display of PyArrow data structures within environments that support ITables. ```python itables.show(pa.table({"A": [1, 2, 3], "B": [4.1, 5.2, 6.3]})) ``` -------------------------------- ### Create a Pandas DataFrame Source: https://github.com/mwouts/itables/blob/main/docs/pandas_style.md Creates a sample Pandas DataFrame with sine and cosine values, used for demonstrating Pandas Style features. ```python x = np.linspace(0, np.pi, 21) df = pd.DataFrame({"sin": np.sin(x), "cos": np.cos(x)}, index=pd.Index(x, name="alpha")) df ``` -------------------------------- ### Display Sample Countries DataFrame Source: https://github.com/mwouts/itables/blob/main/tests/test_notebook.ipynb Retrieve and display a sample DataFrame containing country information using the get_countries() function. This demonstrates the basic rendering of tabular data within the notebook environment. ```python get_countries() ``` -------------------------------- ### Display Table Footer Source: https://github.com/mwouts/itables/blob/main/docs/options/footer.md Use `footer=True` when calling `itables.show()` to display the table footer. Ensure `itables.init_notebook_mode()` has been called. ```python import itables itables.init_notebook_mode() df = itables.sample_dfs.get_countries() itables.show(df, footer=True) ``` -------------------------------- ### Run ITables with DT App (Shiny Core) Source: https://github.com/mwouts/itables/blob/main/apps/shiny/README.md Launch the Shiny application using ITables with the DT package via Shiny Core. This command assumes you are in the project's root directory. ```bash shiny run itables_DT/app-core.py ``` -------------------------------- ### Initialize Notebook Mode (Offline) Source: https://github.com/mwouts/itables/blob/main/tests/test_notebook.ipynb Initialize the itables notebook mode in offline mode. This is the default behavior and is suitable for environments where an internet connection is not consistently available for fetching resources. ```python init_notebook_mode(connected=False) ``` -------------------------------- ### Initialize itables Notebook Mode Source: https://github.com/mwouts/itables/blob/main/docs/options/style.md Initializes itables for use in a Jupyter Notebook environment. This is a prerequisite for displaying interactive tables. ```python import pandas as pd import itables itables.init_notebook_mode() df_small = pd.DataFrame({"a": [2, 1]}) ``` -------------------------------- ### Run ITables Widget App (Shiny Express) Source: https://github.com/mwouts/itables/blob/main/apps/shiny/README.md Launch the Shiny application using the ITables widget with Shiny Express. This command assumes you are in the project's root directory. ```bash shiny run itable_widget/app-express.py ``` -------------------------------- ### Enable Text Selection in Headers Source: https://github.com/mwouts/itables/blob/main/docs/options/text_in_header_can_be_selected.md Demonstrates enabling text selection in table headers. This is the default behavior. ```python import itables itables.init_notebook_mode() df = itables.sample_dfs.get_countries() itables.show(df, "A table in which column headers can be selected") ``` -------------------------------- ### Set Default Layout Options Source: https://github.com/mwouts/itables/blob/main/docs/options/layout.md Configures the default layout for all subsequent iTables displays. This sets the search, pagination, and info elements to specific positions. ```python itables.options.layout = { "topStart": "pageLength", "topEnd": "search", "bottomStart": "info", "bottomEnd": "paging" } # (default value) ``` -------------------------------- ### Run Python Test Suite Source: https://github.com/mwouts/itables/blob/main/docs/developing.md Execute the Python test suite using pytest. This is a basic step to ensure code functionality. ```shell pytest ``` -------------------------------- ### Run ITables with DT App (Shiny Express) Source: https://github.com/mwouts/itables/blob/main/apps/shiny/README.md Launch the Shiny application using ITables with the DT package via Shiny Express. This command assumes you are in the project's root directory. ```bash shiny run itables_DT/app-express.py ``` -------------------------------- ### Configure Column Control Extension in TOML Source: https://github.com/mwouts/itables/blob/main/docs/configuration.md Set up the column control extension to manage table columns, including ordering and searching. ```toml [[columnControl]] target = 0 content = ["order"] [[columnControl]] target = "tfoot" content = ["search"] ``` -------------------------------- ### Remove 'compact' class Source: https://github.com/mwouts/itables/blob/main/docs/options/classes.md Demonstrates how to remove the 'compact' class to create a less dense table. Requires pandas and itables. ```python import pandas as pd import itables itables.init_notebook_mode() df = itables.sample_dfs.get_countries() itables.show(df, classes="display nowrap") ``` -------------------------------- ### Import and Initialize Dark Mode Source: https://github.com/mwouts/itables/blob/main/src/itables/html/init_datatables.html Import the `set_or_remove_dark_class` function from the ITables bundle and call it to apply dark mode. ```javascript import { set_or_remove_dark_class } from 'https://www.unpkg.com/dt_for_itables/dt_bundle.js'; set_or_remove_dark_class(); ``` -------------------------------- ### Set Table Classes in TOML Source: https://github.com/mwouts/itables/blob/main/docs/configuration.md Configure default table classes like 'display' and 'nowrap' to control table appearance. ```toml classes = ["display", "nowrap"] ``` -------------------------------- ### Initialize Notebook Mode for ITables Source: https://context7.com/mwouts/itables/llms.txt Loads the DataTables JavaScript bundle and optionally patches DataFrame display for automatic interactivity. Use `connected=False` for offline use and `all_interactive=False` to disable automatic display. ```python import itables # Auto-display ALL DataFrames as interactive tables (default) itables.init_notebook_mode() # Offline mode — embeds the DataTables bundle inside the notebook itables.init_notebook_mode(connected=False) # Only activate explicit show() calls, not automatic display itables.init_notebook_mode(all_interactive=False) import pandas as pd df = pd.DataFrame({"country": ["France", "Germany", "Japan"], "pop_M": [68, 84, 125]}) df # → displayed as interactive DataTable (because all_interactive=True) ``` -------------------------------- ### itables.options — Global defaults Source: https://context7.com/mwouts/itables/llms.txt Allows setting global default options for all ITables renderings. Attributes of `itables.options` can be modified to change default behaviors like `maxBytes`, `show_dtypes`, `buttons`, `column_filters`, and table styling. ```APIDOC ## itables.options — Global defaults `itables.options` is a module-level object whose attributes define the default value for every option accepted by `show` and `to_html_datatable`. Any attribute assignment takes effect immediately for all subsequent calls. ```python import itables # Increase the downsampling threshold (default "64KB") itables.options.maxBytes = "256KB" # Show dtypes row in header for all tables itables.options.show_dtypes = True # Always add export buttons globally itables.options.buttons = ["pageLength", "copyHtml5", "csvHtml5", "excelHtml5"] # Add per-column search filters by default itables.options.column_filters = "footer" # Change table appearance: less compact, explicit width itables.options.classes = ["display", "nowrap"] itables.options.style = "table-layout:auto;width:auto;margin:auto" ``` ``` -------------------------------- ### Set Fixed Width for All Columns Source: https://github.com/mwouts/itables/blob/main/docs/options/column_defs.md Use `columnDefs` with `targets: "_all"` to set a fixed width for all columns. Ensure `autoWidth` is `False` and `style` is adjusted if necessary to prevent overrides. ```python import itables itables.init_notebook_mode() df = itables.sample_dfs.get_countries() itables.show( df, columnDefs=[{"width": "120px", "targets": "_all"}], style="width:1200px", autoWidth=False, ) ``` -------------------------------- ### Initialize itables and Show DataFrame with RowGroup Source: https://github.com/mwouts/itables/blob/main/docs/options/row_group.md Initializes itables for notebook mode and displays a Pandas DataFrame with row grouping enabled. The data is sorted by the 'region' column, and row grouping is applied to the second column (index 1). The second column is also hidden to avoid data duplication. ```python import itables itables.init_notebook_mode() df = itables.sample_pandas_dfs.get_countries() itables.show( df.sort_values("region"), rowGroup={"dataSrc": 1}, columnDefs=[{"targets": 1, "visible": False}], ) ``` -------------------------------- ### Globally Enable KeyTable Navigation in itables Source: https://github.com/mwouts/itables/blob/main/docs/options/keys.md Set `itables.options.keys = True` to enable arrow key navigation for all tables displayed by itables. This is a global setting. ```python itables.options.keys = True ``` -------------------------------- ### Display DataFrame with ITable Widget in Marimo Source: https://github.com/mwouts/itables/blob/main/docs/apps/marimo.md Use the `ITable` widget for displaying DataFrames in Marimo. Ensure `pandas` and `itables.widget.ITable` are imported. ```python import pandas as pd from itables.widget import ITable df = pd.DataFrame({"x": [2, 1, 3]}) ITable(df) ``` -------------------------------- ### Check Active ITables Configuration File Source: https://context7.com/mwouts/itables/llms.txt Verify which configuration file ITables is currently using. This can be done via a subprocess call or directly within Python. ```python import subprocess subprocess.run(["python", "-m", "itables.show_config"]) ``` ```python from itables.config import get_config_file print(get_config_file()) # → PosixPath('/your/project/itables.toml') or None ``` -------------------------------- ### Basic Column Controls - itables Source: https://github.com/mwouts/itables/blob/main/docs/options/column_control.md Demonstrates the basic usage of columnControl with order, colVisDropdown, and searchDropdown options. When using columnControl for ordering, it's recommended to disable default ordering indicators. ```python itables.show( df, columnControl=["order", "colVisDropdown", "searchDropdown"], ordering={"indicators": False, "handler": False}, ) ``` -------------------------------- ### Initialize itables Offline Source: https://github.com/mwouts/itables/blob/main/src/itables/html/init_notebook_offline.html This script initializes itables for offline use by injecting CSS and loading necessary JavaScript modules. It checks if itables is already initialized to prevent redundant loading and dispatches an event when the version is ready. ```javascript function injectCSS(base64CSS) { const cssText = atob(base64CSS); const style = document.createElement('style'); style.textContent = cssText; document.head.appendChild(style); } async function injectModule(base64JS) { const jsText = atob(base64JS); const blob = new Blob([jsText], { type: 'application/javascript' }); const url = URL.createObjectURL(blob); const module = await import(url); URL.revokeObjectURL(url); return module; } if (!window._itables_underscore_version) { injectCSS("dt_css_b64"); window._itables_underscore_version = injectModule("dt_src_b64"); window._itables_underscore_version.then(() => { window.dispatchEvent(new Event("itables-version-ready")); }); } ``` -------------------------------- ### Update Project Dependencies Source: https://github.com/mwouts/itables/blob/main/packages/dt_for_itables/README.md Use this command to update all project dependencies to their latest compatible versions. It's recommended to check for outdated packages afterwards. ```bash npm update --save ``` -------------------------------- ### Display Column Filters with MultiIndex Columns Source: https://github.com/mwouts/itables/blob/main/docs/options/column_filters.md Demonstrates that column filters work correctly with dataframes that have multi-index columns. ```python itables.sample_dfs.get_dict_of_test_dfs()["multiindex"] ``` -------------------------------- ### Configure Global Defaults for ITables Options Source: https://context7.com/mwouts/itables/llms.txt Modify global default settings for ITables using `itables.options`. Attributes like `maxBytes`, `show_dtypes`, `buttons`, `column_filters`, `classes`, and `style` can be set to affect all subsequent table renderings. ```python import itables # Increase the downsampling threshold (default "64KB") itables.options.maxBytes = "256KB" # Show dtypes row in header for all tables itables.options.show_dtypes = True # Always add export buttons globally itables.options.buttons = ["pageLength", "copyHtml5", "csvHtml5", "excelHtml5"] # Add per-column search filters by default itables.options.column_filters = "footer" # Change table appearance: less compact, explicit width itables.options.classes = ["display", "nowrap"] itables.options.style = "table-layout:auto;width:auto;margin:auto" ``` -------------------------------- ### Display a wide DataFrame with display options Source: https://github.com/mwouts/itables/blob/main/docs/pandas_dataframes.md Shows a wide DataFrame with specific display options: `maxBytes`, `maxColumns`, and `scrollX`. This is useful for large tables that might otherwise be truncated or unmanageable. ```python itables.show(dict_of_test_dfs["wide"], maxBytes=100000, maxColumns=100, scrollX=True) ``` -------------------------------- ### Display DataFrame with custom lengthMenu and pageLength Source: https://github.com/mwouts/itables/blob/main/docs/options/length_menu.md Displays a DataFrame with a custom selection of entries per page (2, 5, 10, 20, 50) and sets the default page length to 5. ```python itables.show(df, lengthMenu=[2, 5, 10, 20, 50], pageLength=5) ``` -------------------------------- ### Display 'capital' DataFrame Source: https://github.com/mwouts/itables/blob/main/docs/pandas_dataframes.md Renders the 'capital' DataFrame. This is a standard DataFrame display. ```python itables.show(dict_of_test_dfs["capital"]) ``` -------------------------------- ### Display Buttons in ITables Source: https://github.com/mwouts/itables/blob/main/docs/options/buttons.md Use the `buttons` argument in the `show` function to display export and copy buttons. The `pageLength` button is included to keep the pagination control. ```python import itables itables.init_notebook_mode() df = itables.sample_dfs.get_countries() itables.show(df, buttons=["pageLength", "copyHtml5", "csvHtml5", "excelHtml5"]) ``` -------------------------------- ### Global and Per-Table CSS Styling with ITables Source: https://context7.com/mwouts/itables/llms.txt Apply custom CSS globally using IPython.display.HTML or per-table via the 'classes' and 'style' arguments. The 'classes' argument maps to DataTables CSS class names, and 'style' applies inline CSS to the table container. ```python from IPython.display import HTML, display import itables import pandas as pd itables.init_notebook_mode() # Global CSS override for all tables in the notebook display(HTML(""" """)) # Per-table custom class + CSS display(HTML("")) df = pd.DataFrame({"col_a": range(5), "col_b": [x**2 for x in range(5)]}) itables.show( df, classes="display nowrap mono-table", style="table-layout:auto;width:60%;float:right", caption="Right-aligned mono table", ) ``` ```python # Compact vs. full layout itables.show(df, classes=["display", "nowrap"]) # compact (default) itables.show(df, classes=["display", "nowrap", "stripe"]) # striped rows itables.show(df, classes=["display", "cell-border"]) # cell borders ``` -------------------------------- ### Display DataFrame with Regex Search Source: https://github.com/mwouts/itables/blob/main/docs/options/search.md Displays a DataFrame with an initial search query that uses regular expressions. The search is configured to be case-insensitive. ```python df = itables.sample_dfs.get_countries() itables.show(df, search={"regex": True, "caseInsensitive": True, "search": "s.ain"}) ``` -------------------------------- ### Initialize ITables with Mixed Data Types Source: https://github.com/mwouts/itables/blob/main/tests/data/test_to_html_datatable/int_float_str.html Use this snippet to initialize an ITables instance with a table containing integer, float, and string columns. It includes custom column definitions to control how data is rendered and sorted. ```javascript import { ITable, jQuery as $ } from 'https://www.unpkg.com/dt_for_itables@{dt_for_itables_version}/dt_bundle.js'; document.querySelectorAll("#table_id:not(.dataTable)").forEach(table => { if (!(table instanceof HTMLTableElement)) return; let dt_args = { "classes": ["display", "nowrap", "compact"], "columnDefs": [{ "render": "function (data, type, row, meta) { return type === 'sort' || type === 'type' ? data[1] : data[0]; }", "targets": [1] }], "data_json": "[[0, [\"5.000000\", 5.0], \"a\"], [1, [\"4.949495\", 4.94949494949495], \"b\"], [2, [\"4.898990\", 4.898989898989899], \"c\"], [3, [\"4.848485\", 4.848484848484849], \"d\"], [4, [\"4.797980\", 4.797979797979798], \"e\"]]", "keys_to_be_evaluated": [["columnDefs", 0, "render"]], "layout": {"bottomEnd": null, "bottomStart": null, "topEnd": null, "topStart": null}, "order": [], "style": {"caption-side": "bottom", "margin": "auto", "table-layout": "auto", "width": "auto"}, "table_html": "\n \n \n \n \n \n \n
intfloatstr
", "text_in_header_can_be_selected": true }; new ITable(table, dt_args); }); ``` -------------------------------- ### Display DataFrame with Default Downsampling Source: https://github.com/mwouts/itables/blob/main/docs/downsampling.md Displays a DataFrame. If the DataFrame's data size exceeds the configured `maxBytes`, it will be downsampled, and a warning will be shown. ```python df ``` -------------------------------- ### Configure offline internationalization Source: https://github.com/mwouts/itables/blob/main/docs/custom_extensions.md Loads a JSON translation file into itables.options.language for offline use. Requires the translation file to be present locally. ```python import json with open("fr-FR.json") as fp: itables.options.language = json.load(fp) ``` -------------------------------- ### Add 'cell-border' class Source: https://github.com/mwouts/itables/blob/main/docs/options/classes.md Illustrates adding the 'cell-border' class for additional styling options. Requires pandas and itables. ```python itables.show(df, classes="display nowrap compact cell-border") ``` -------------------------------- ### Enable Excel Export Button in TOML Source: https://github.com/mwouts/itables/blob/main/docs/configuration.md Add the 'excelHtml5' button to the configuration to enable Excel export functionality for tables. ```toml buttons = ["pageLength", "copyHtml5", "csvHtml5", "excelHtml5"] ``` -------------------------------- ### Display DataFrame with Custom Layout Source: https://github.com/mwouts/itables/blob/main/docs/options/layout.md Shows a DataFrame with a specific layout configuration, placing the search bar at the top-start and disabling the top-end element. ```python itables.show(df, layout={"topStart": "search", "topEnd": None}) ``` -------------------------------- ### Configure FixedHeader in itables.toml Source: https://github.com/mwouts/itables/blob/main/docs/options/fixed_header.md Alternatively, you can set `fixedHeader = true` in your `itables.toml` configuration file to enable this option globally. ```toml fixedHeader = true ```