great-tables

repository·main·Indexed 25 days ago

https://github.com/posit-dev/great-tables

A Python library for creating highly customizable, publication-quality display tables from Pandas or Polars DataFrames. It provides the GT class to compose tables with headers, footers, stubs, and spanners, and includes specialized methods for formatting currencies, dates, numbers, and images. Tables can be rendered to HTML or image files, with a .show() method available for console environments.

Tokens
27K
Snippets
67
Records
138
Agent score
82%

What's inside great-tables

  1. View tables in the console using show()

    main
    Great Tables do not print directly to the console. To view a table while working in a console, call the .show() method on your table object. This will open the rendered HTML table in your default web browser.
  2. Create a display table with Great Tables

    main

    Great Tables works by taking a Pandas or Polars DataFrame and applying various components and formatting methods. You can add headers, format currencies, dates, and numbers, or hide specific columns. Tables are typically rendered to HTML or an image file. In a console environment, you can use the .show() method to open the HTML table in your default browser.

    from great_tables import GT
    from great_tables.data import sp500
    
    # Define the start and end dates for the data range
    start_date = "2010-06-07"
    end_date = "2010-06-14"
    
    # Filter sp500 using Pandas to dates between `start_date` and `end_date`
    sp500_mini = sp500[(sp500["date"] >= start_date) & (sp500["date"] <= end_date)]
    
    # Create a display table based on the `sp500_mini` table data
    (
        GT(sp500_mini)
        .tab_header(title="S&P 500", subtitle=f"{start_date} to {end_date}")
        .fmt_currency(columns=["open", "high", "low", "close"])
        .fmt_date(columns="date", date_style="wd_m_day_year")
        .fmt_number(columns="volume", compact=True)
        .cols_hide(columns="adj_close")
    )
  3. Use conditional sections in merge patterns

    main

    When defining a pattern for ColMergeInfo, you can use <<...>> to create conditional sections. If any column referenced within the <<...>> block is None (missing), the entire contents of that block will be omitted from the resulting string.

    This is useful for avoiding trailing separators or empty parentheses when data is missing.

    >>> info = ColMergeInfo(vars=["a", "b"], rows=[0], type="merge", pattern="{0}<< ({1})>>")
    >>> info.merge("John", None)
    'John'
  4. Format numbers and display images in Great Tables

    main

    Enhance table data using formatting methods:

    • .fmt_number(): Formats numeric columns. Use scale_by to adjust values (e.g., converting large numbers to millions) and decimals to set precision.
    • .fmt_image(): Renders images in a column. Specify the column name and the path where the image files are located.
    (
        GT(res, rowname_col="Rank")
        .fmt_number(["Total Earnings", "Off-the-Field Earnings"], scale_by = 1/1_000_000, decimals=1)
        .fmt_image("icon", path="./")
    )
  5. Use HTML in table headers with `html()`

    main

    To retain and render HTML elements within a table header, pass the desired HTML string to the html() helper function inside the tab_header() method.

    from great_tables import GT, md, html
    from great_tables.data import gtcars
    
    gtcars_mini = gtcars[['mfr', 'model', 'msrp']].head(5)
    
    ( 
        GT(gtcars_mini)
        .tab_header(
            title=md("Data listing <strong>gtcars</strong>"),
            subtitle=html("From <span style='color:red;'>gtcars</span>")
        )
    )
  6. Format numbers and column labels in Great Tables

    main

    Customize how data appears in your table using .fmt_number() to scale values (e.g., converting large numbers to millions) and .cols_label() to rename columns for display.

    (
        GT(res, rowname_col="Rank")
        .cols_label(**{
            "Total Earnings": "Total $M",
            "Off-the-Field Earnings": "Off field $M",
            "Off-the-Field Earnings Perc": "Off field %"
        })
        .fmt_number(["Total Earnings", "Off-the-Field Earnings"], scale_by = 1/1_000_000, decimals=1)
    )
  7. Create a table with headers, spanners, and source notes

    main

    Use the GT class to build a table. You can add a title using .tab_header(), group columns using .tab_spanner(), and add a footer/source note using .tab_source_note(). For the source note, use the md() function to allow Markdown and HTML styling.

    (
        GT(res, rowname_col="Rank")
        .tab_header("Highest Paid Athletes in 2023")
        .tab_spanner("Earnings", cs.contains("Earnings"))
        .tab_source_note(
            md(
                '<br><div style="text-align: center;">'
                "Original table: [@LisaHornung_](https://twitter.com/LisaHornung_/status/1752981867769266231)"
                " | Sports icons: [Firza Alamsyah](https://thenounproject.com/browse/collection-icon/sports-96427)"
                " | Data: Forbes"
                "</div>"
                "<br>"
            )
        )
    )
  8. Create a table with headers, spanners, and custom labels

    main

    Use GT() to initialize a table and chain methods to add structural elements:

    • .tab_header(): Adds a title and subtitle to the table.
    • .tab_spanner(): Groups columns under a common header using a selector.
    • .cols_label(): Renames columns for display using a dictionary mapping current names to new labels.
    (
        GT(res, rowname_col="Rank")
        .tab_header("Highest Paid Athletes in 2023")
        .tab_spanner("Earnings", cs.contains("Earnings"))
        .cols_label(**{
            "Total Earnings": "Total $M",
            "Off-the-Field Earnings": "Off field $M",
            "Off-the-Field Earnings Perc": "Off field %"
        })
    )