ipydatagrid

repository·main·Indexed 20 days ago

https://github.com/jupyter-widgets/ipydatagrid

A high-performance, feature-rich DataGrid widget for Jupyter Notebook and JupyterLab. Version 1.4.0 provides advanced data visualization capabilities, including custom renderers, two-way data binding for selections, and conditional formatting via Vega Expressions and Python functions. It supports cell editing, programmatic value updates, auto-fitting column widths, and integration with bqplot Scales.

Tokens
16.7K
Snippets
49
Records
60
Agent score
69%

What's inside ipydatagrid

  1. Key features of ipydatagrid

    main

    ipydatagrid is a fast, high-performance DataGrid widget for Jupyter Notebook and JupyterLab with the following capabilities:

    • High Performance: Fully integrated with ipywidgets for efficient data handling.
    • Customizable Rendering: Use a variety of renderers to customize how data is represented in the grid.
    • Sophisticated Selections: Supports a selection model with two-way data binding.
    • Conditional Formatting: Powered by Vega Expressions to style cells based on data values.
    • Integration: Works with bqplot Scales if the bqplot extensions are also installed.
  2. Install ipydatagrid

    main

    You can install ipydatagrid using pip or conda. If you are using JupyterLab, ensure you are using version 3 or higher.

    If you are using Jupyter Notebook 5.2 or earlier, you may need to manually enable the nbextension.

    # Using pip
    pip install ipydatagrid
    
    # Using conda
    conda install -c conda-forge ipydatagrid
    
    # For Jupyter Notebook 5.2 or earlier
    jupyter nbextension enable --py [--sys-prefix|--user|--system] ipydatagrid
  3. Install ipydatagrid for development

    main

    To install ipydatagrid for development purposes, clone the repository and install it in editable mode.

    Jupyter Notebook Setup

    To enable the development installation for Jupyter Notebook:

    jupyter nbextension install --py --symlink --sys-prefix ipydatagrid
    jupyter nbextension enable --py --sys-prefix ipydatagrid

    Note: The --symlink argument works on Linux or OS X to allow in-place JavaScript modifications, but is not available on Windows.

    JupyterLab Setup

    To enable the development installation for JupyterLab:

    jupyter labextension develop . --overwrite

    TypeScript Development Workflow

    If you are modifying TypeScript code, use jlpm watch to automatically rebuild on changes while running your Jupyter server in a separate terminal.

    git clone https://github.com/jupyter-widgets/ipydatagrid.git
    cd ipydatagrid
    conda install ipywidgets=8 jupyterlab
    pip install -ve .
  4. Define cell logic with Python expressions using Expr

    main

    The Expr class allows you to write logic in Python and automatically converts it into a Vega expression using py2vega. You can pass either a Python expression as a string or a Python function.

    This is useful for complex conditional formatting that is easier to write in Python than in Vega syntax.

    from ipydatagrid import Expr
    
    def horsepower_coloring(cell):
        if cell.value < 100:
            return "red"
        elif cell.value < 150:
            return "orange"
        else:
            return "green"
    
    # Use the function with Expr
    renderer = TextRenderer(background_color=Expr(horsepower_coloring))
  5. How frontend transforms (sort and filter) are applied

    main

    The DataGrid can apply transformations to the dataset via _transforms.

    • Sorting: A sort transform takes a column and a desc (boolean, defaults to False) parameter to reorder the data.
    • Filtering: A filter transform uses an operator, a column, and a value to subset the data.

    When transforms are updated, the widget recalculates the _transformed_data based on the original __dataframe_reference and notifies the frontend via tick() to sync the row count and view.

  6. Define cell logic with VegaExpr

    main

    The VegaExpr class allows you to use Vega expressions to dynamically calculate cell attributes. This is highly performant as the logic is executed in the browser.

    Available constants and functions in the expression scope include:

    • value: The cell's value.
    • x, y: Cell position in pixels.
    • width, height: Dimensions of the cell.
    • row, column: The cell's position in the grid.
    • default_value: The fallback value if the expression condition is not met.
    from ipydatagrid import VegaExpr
    
    # Example: Red background if value < 150, otherwise green
    renderer = TextRenderer(background_color=VegaExpr("value < 150 ? 'red' : 'green'"))
  7. Navigate cells during editing

    main

    When editing a cell, the cursor cell is the active cell. If a single cell is selected, the cursor is that cell. If a rectangle is selected, the cursor is the cell where the selection started.

    You can move the cursor using these keyboard shortcuts:

    • Down: Enter
    • Up: Shift + Enter
    • Right: Tab
    • Left: Shift + Tab
  8. Understand the ipydatagrid styling priority layers

    main

    Styling in ipydatagrid is applied across three hierarchical layers. Understanding this hierarchy is essential for effective customization:

    1. Column-specific renderers (Highest Priority): Specified via the renderers property. These override both grid_style and default renderers.
    2. Overall grid style (Medium Priority): Defined via the grid_style property. These override the default renderers.
    3. Default renderers (Lowest Priority): The base styles for header_renderer (columns), corner_renderer (top left corner), and default_renderer (body cells).
  9. Use StreamingDataGrid for large datasets

    main

    The StreamingDataGrid class allows for lazy data requests to the back-end, which reduces the initial loading time and the memory footprint of the grid.

    Requirements & Limitations:

    • Requires a live kernel (it will not work in static HTML exports via nbconvert).
    • The tick() method is used to notify the grid that the underlying DataFrame has changed, but it cannot be called inside a loop. Because the kernel is busy executing the loop, it cannot respond to the front-end's viewport requests until the loop finishes.
    from ipydatagrid import StreamingDataGrid
    import pandas as pd
    import numpy as np
    
    dataframe = pd.DataFrame(np.random.randn(100, 100))
    
    streaming_datagrid = StreamingDataGrid(
        dataframe,
        debounce_delay=50
    )
    streaming_datagrid
  10. Use custom cell renderers in DataGrid

    main

    You can customize how data is displayed in cells by applying renderers to specific columns or as a default_renderer for the entire grid.

    Supported renderer types include:

    • TextRenderer: For standard text display.
    • BarRenderer: For displaying data as bars within the cell.
    • ImageRenderer: For displaying images.

    Renderer attributes like background_color, text_color, font, and bar_color can be set using:

    1. A static value (e.g., 'red', '#ffffff').
    2. A bqplot scale (e.g., LinearScale, ColorScale).
    3. A VegaExpr instance for Vega-based expressions.
    4. An Expr instance for Python-based expressions.
    from ipydatagrid import DataGrid, TextRenderer, BarRenderer, ImageRenderer
    
    # Define renderers for specific columns
    renderers = {
        "Column_Name": TextRenderer(background_color="green"),
        "Value_Column": BarRenderer(bar_color="blue")
    }
    
    datagrid = DataGrid(df, renderers=renderers)
  11. Enable cell editing in DataGrid

    main

    By default, DataGrid instances are not editable. To allow users to edit cells via double-clicking or typing, set the editable property to True. Enabling editing automatically sets the selection mode to cell if it was previously set to none.

    from ipydatagrid import DataGrid
    import pandas as pd
    
    df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
    datagrid = DataGrid(df, editable=True, layout={'height': '200px'})
    datagrid
  12. Configure DataGrid selection modes

    main

    The DataGrid supports different selection behaviors via the selection_mode parameter. By default, selection is disabled ('none').

    Available modes:

    • 'cell': Clicking selects only the specific cell under the cursor.
    • 'row': Clicking selects the entire row under the cursor.
    • 'column': Clicking selects the entire column under the cursor.
    • 'none': Disables all selections (default).
    from ipydatagrid import DataGrid
    import pandas as pd
    
    df = pd.DataFrame(data)
    datagrid = DataGrid(df, selection_mode="cell")