tabulate

repository·master·Indexed 25 days ago

https://github.com/astanin/python-tabulate

A Python library and CLI utility for pretty-printing tabular data. It supports various input types including lists, dicts, NumPy arrays, and pandas DataFrames, and can output in numerous text-based formats such as Markdown, HTML, LaTeX, and various grid-based styles via the tablefmt argument.

Tokens
6.1K
Snippets
14
Records
35
Agent score
83%

What's inside tabulate

  1. ANSI escape code support

    master
    tabulate supports ANSI escape codes (for colors and styles). It calculates column widths by ignoring non-printable ANSI sequences, ensuring that the visual alignment is correct while preserving the actual styling in the output. It also correctly handles escaped hyperlinks by basing column width on the visible text rather than the underlying URL.
  2. Install tabulate library and CLI

    master

    To install the tabulate Python library and its command-line utility, use pip.

    Standard installation:

    pip install tabulate

    User-only installation: To install the library only for the current user:

    pip install tabulate --user

    Library-only installation (Unix-like): To install just the library without the CLI utility on Unix-like systems:

    TABULATE_INSTALL=lib-only pip install tabulate

    Library-only installation (Windows):

    set TABULATE_INSTALL=lib-only
    pip install tabulate
    pip install tabulate
  3. Enable wide character (CJK) support

    master

    To properly align tables containing wide characters (Chinese, Japanese, or Korean glyphs), you must install the wcwidth library. You can install it as an extra for tabulate using:

    pip install tabulate[widechars]

    Wide character support is enabled automatically if wcwidth is present. To manually disable this support, set the global module-level flag tabulate.WIDE_CHARS_MODE = False.

  4. Understand the TableFormat and DataRow abstractions

    master

    The library uses two main data structures to define how tables are rendered:

    1. TableFormat: A namedtuple that defines the structure of the table, including lineabove, linebelowheader, linebetweenrows, linebelow, headerrow, datarow, padding, and with_header_hide. Elements can be None, a Line tuple, or a formatting function.
    2. DataRow: A @dataclass used to define how rows (headers or data) are constructed, containing begin, sep, end, and an optional escape_map.
  5. Use the tabulate CLI to pretty-print tabular data

    master

    The tabulate command-line interface allows you to convert various input file formats (RSV, CSV, JSONL) into formatted tables. You can provide filenames as arguments or read from stdin by using - or omitting the filename.

    Usage: tabulate [options] [FILE ...]

    Example (reading from stdin):

    cat data.csv | tabulate --format github
    tabulate [options] [FILE ...]
  6. Configure table headers with headers argument

    master

    The headers argument allows you to define column labels. It accepts several types of input:

    • A list of strings: Explicitly defines the column names.
    • "firstrow": Uses the first row of the data as the header.
    • "keys": Uses the keys of a dictionary/dataframe, or column indices (works for NumPy record arrays, lists of dictionaries, or named tuples).
    • A dictionary: When the data is a list of dictionaries, you can pass a dictionary to map existing keys to new column labels.
  7. Select a table format with `tablefmt`

    master

    The tablefmt argument allows you to choose from various visual styles for your table. Formats include grid-based styles (like heavy_outline, fancy_grid), CLI-emulating styles (like psql, presto), and markup-specific styles (like html, latex, mediawiki, jira, asciidoc, rst, orgtbl, textile).

    print(tabulate(table, headers, tablefmt="heavy_outline"))
  8. Use the tabulate() function

    master

    The core of the library is the tabulate function. It accepts tabular data (such as a list of lists, list of dicts, or a pandas DataFrame) and returns a formatted plain-text string.

    Supported data types:

    • list of lists or another iterable of iterables
    • list or another iterable of dicts (keys as columns)
    • dict of iterables (keys as columns)
    • list of dataclasses (field names as columns)
    • two-dimensional NumPy array
    • NumPy record arrays (names as columns)
    • pandas.DataFrame
    from tabulate import tabulate
    
    table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
             ["Moon",1737,73.5],["Mars",3390,641.85]]
    print(tabulate(table))
  9. Handle multiline cells with maxcolwidths

    master

    You can provide explicit newline characters (\n) in your data to create multiline cells. For automatic wrapping, use the maxcolwidths argument, which accepts a list of integers (one per column) or a single integer to apply to all columns. Use None for columns that should not be wrapped.

    Wrapping behavior is controlled by:

    • break_long_words (default: True): If True, words longer than the width will be broken.
    • break_on_hyphens (default: True): If True, wrapping prefers whitespaces and hyphens.
    >>> print(tabulate([["John Smith", "Middle Manager"]], headers=["Name", "Title"], tablefmt="grid", maxcolwidths=[None, 8]))
    +------------+---------+
    | Name       | Title   |
    +============+=========+
    | John Smith | Middle  |
    |            | Manager |
    +------------+---------+
  10. Handle missing values and type deduction

    master

    When data is missing (None or empty strings), tabulate uses the remaining data in the column to infer the column type. This type influences how objects (like fractions.Fraction) are rendered. You can specify how to display missing values using the missingval argument.

    from fractions import Fraction
    test_table = [
        [None, "1.23423515351", Fraction(1, 3)],
        [Fraction(56789, 1000000), 12345.1, b"abc"],
        ["", b"", None],
        [Fraction(10000, 3), None, ""],
    ]
    print(tabulate(test_table, floatfmt=",.5g", missingval="?"))
  11. Configure column alignment

    master

    By default, tabulate aligns numbers by their decimal point (or right-aligns integers) and text to the left. You can override this using several arguments:

    • numalign / stralign: Set a specific alignment for all numeric or string columns (right, center, left, decimal, or None).
    • colglobalalign: Sets a global alignment for all columns (right, center, left, decimal).
    • colalign: A list or tuple for column-specific alignment. Use 'global' to inherit the global setting. Possible values: right, center, left, decimal, None, or 'global'.
    • disable_numparse: Set to True to prevent tabulate from attempting to parse strings as numbers.