Table classes
This class creates a table that can be pretty printed in any terminal that supports ANSI escape sequences.
Creating a table
- class ansitable.ANSITable(*pos, colsep=1, offset=0, border=None, bordercolor=None, ellipsis=True, columns=None, header=True, color=True)[source]
Bases:
object- __init__(*pos, colsep=1, offset=0, border=None, bordercolor=None, ellipsis=True, columns=None, header=True, color=True)[source]
Create a table object
- Parameters:
colsep (int) – Blank padding on each side of column separator, defaults to 1
offset (int) – Horizontal offset of the whole table, defaults to 0
border (Border | None) – Type of border, see table below, defaults to None
bordercolor (str | None) – Name of color to draw border in, defaults to None
ellipsis (bool) – truncated lines are shown with an ellipsis, defaults to True
columns (int | None) – if no positional column names/
Columnobjects are given, create this many empty placeholder columns instead, defaults to Noneheader (bool) – Show table header, defaults to True
color (bool) – enable color output for this table instance (also gated by global
options()settings), defaults to True
- Raises:
A table can be created in several different ways:
table = ANSITable("col1", "column 2 has a big header", "column 3") table = ANSITable( Column("col1"), Column("column 2 has a big header", "{:.3g}"), Column("column 3", "{:-10.4f}") ) table = ANSITable() table.addcolumn("col1") table.addcolumn("column 2 has a big header", fmt="{:.3g}") table.addcolumn("column 3", fmt="{:-10.4f}")
The first option is quick and easy but does not allow any control of formatting or alignment.
Border
Description
ascii
Use ASCII +-| characters
thin
Use ANSI thin box-drawing characters
round
Use ANSI thin box-drawing characters with rounded corners
thick
Use ANSI thick box-drawing characters
double
Use ANSI double-line box-drawing characters
- addcolumn(name, **kwargs)[source]
Add a column to the table
An alternative way to create a table, column at a time.
Example:
>>> from ansitable import ANSITable >>> table = ANSITable() >>> table.addcolumn("col1") >>> table.addcolumn("column 2 has a big header", fmt="{:.3g}") >>> table.addcolumn("column 3", fmt="{:-10.4f}")
Note
Additional arguments are passed directly to
Column.
- static Pandas(df, **kwargs)[source]
Create an ANSITable from a Pandas dataframe
- Parameters:
df (
DataFrame) – Pandas dataframekwargs (
Any) – additional arguments to pass to the ANSITable constructor
- Return type:
- Returns:
an ansitable object
Example:
>>> import pandas as pd >>> from ansitable import ANSITable >>> df = pd.DataFrame({"calories": [420, 380, 390], "duration": [50, 40, 45]}) >>> table = ANSITable.Pandas(df, border="thin") >>> table.print() ┌──────────┬──────────┐ │ calories │ duration │ ├──────────┼──────────┤ │ 420 │ 50 │ │ 380 │ 40 │ │ 390 │ 45 │ └──────────┴──────────┘
Note
options for header and column alignment and format are not supported
- class ansitable.Column(name, fmt='{}', width=None, colcolor=None, colbgcolor=None, colstyle=None, colalign='>', headcolor=None, headbgcolor=None, headstyle=None, headalign='>')[source]
Bases:
object- __init__(name, fmt='{}', width=None, colcolor=None, colbgcolor=None, colstyle=None, colalign='>', headcolor=None, headbgcolor=None, headstyle=None, headalign='>')[source]
Create a table column
- Parameters:
name (str) – Name of column, also the column heading
fmt (str | Callable[[Any], str] | None) – Python format string, defaults to “{}”
width (int | None) – Column width, defaults to auto-fit
colcolor (str | None) – Color of column text, defaults to None
colbgcolor (str | None) – Color of column background, defaults to None
colstyle (Style | None) – Column text style, see table below, defaults to None
colalign (Align) – Column data alignment, see table below, defaults to “>”
headcolor (str | None) – Color of heading text, defaults to None
headbgcolor (str | None) – Color of heading background, defaults to None
headstyle (Style | None) – Heading text style, see table below, defaults to None
headalign (Align | None) – Heading text alignment, see table below, defaults to “>”
The
Columnobject can passed to theANSITableconstructor or toaddcolumn()to specify the format of a column in a table.For header or data cell alignment:
Alignment
Description
“<”
Left
“^”
Centre
“>”
Right (default)
For header or data cell alignment text style:
Style
Description
bold
bold font
dim
low brightness font
underlined
text is underlined
blink
text is blinking
reverse
text and background colors are reversed
The implementation of these options depends heavily on the terminal emulator used.
- name: str
- fmt: str | Callable[[Any], str] | None
- formatted: list[str | None]
- fgcolor: list[str | None]
- bgcolor: list[str | None]
- style: list[Style | None]
- table: ANSITable | None
- colcolor: str | None
- colbgcolor: str | None
- colstyle: Style | None
- colalign: Align
- headcolor: str | None
- headbgcolor: str | None
- headstyle: Style | None
- headalign: Align
- width: int | None
- maxwidth: int
- class ansitable.Cell(text, fgcolor=None, bgcolor=None, style=None)[source]
Bases:
object- __init__(text, fgcolor=None, bgcolor=None, style=None)[source]
Override the color and style of a cell
- Parameters:
text (Any) – cell text, converted to
strif not alreadyfgcolor (str | None) – foreground color, defaults to None
bgcolor (str | None) – background color, defaults to None
style (Style | None) – text style, one of
"bold","dim","underlined","blink","reverse", defaults to None
Example:
>>> from ansitable import ANSITable, Cell >>> table = ANSITable("col1", "column 2 has a big header", "column 3") >>> table.row("aaaaaaaaa", 2.2, 3) >>> table.row("bbbbbbbbbbbbb", -5.5, 6) >>> table.row(Cell("ccccccc", bgcolor="red"), 8.8, -9) >>> table.print() col1 column 2 has a big header column 3 aaaaaaaaa 2.2 3 bbbbbbbbbbbbb -5.5 6 ccccccc 8.8 -9
Will print a table with the first cell in the last row having a red background. The colors and style override those specified when the column was created or specified for a row.
- text: str
- fgcolor: str | None
- bgcolor: str | None
- style: Style | None
- column: Column | None
- row: int | None
Adding a row
- class ansitable.ANSITable(*pos, colsep=1, offset=0, border=None, bordercolor=None, ellipsis=True, columns=None, header=True, color=True)[source]
Bases:
object- row(*values, fgcolor=None, bgcolor=None, style=None)[source]
Add a row of data
- Parameters:
values (Any) – data items for the row. These can be of any type that can be converted to a string for display, eg. numbers, strings or objects with a
__str__method. TheCellencapsulates a value and allows the color or style defaults of the row or column to be overriden.fgcolor (str | None) – foreground color override for all columns in the row, defaults to None
bgcolor (str | None) – background color override for all columns in the row, defaults to None
style (Style | None) – style override for all columns in the row, defaults to None
- Raises:
ValueError – invalid format string for the data provided
- Return type:
None
table.row(d1, d2, ... dN)add data items that comprise a row of the table.Nis the number of columns.The data items can be any type, but the format string specified at table creation must be compatible.
The column data is formatted with the color and style given when the
Columnwas created, but it can be overridden for a specific row by specifying the optionsfgcolor,bgcolor, orstyle.Celloverrides the color and style of a cell specified for a column and a row.
Display a table
- class ansitable.ANSITable(*pos, colsep=1, offset=0, border=None, bordercolor=None, ellipsis=True, columns=None, header=True, color=True)[source]
Bases:
object- print(file=None)[source]
Print the table
- Parameters:
file (TextIO | None) – Print the table to this file, defaults to stdout
- Return type:
None
Example:
>>> from ansitable import ANSITable >>> table = ANSITable("col1", "column 2 has a big header", "column 3", border="ascii") >>> table.row("aaaaaaaaa", 2.2, 3) >>> table.row("bbbbbbbbbbbbb", -5.5, 6) >>> table.row("ccccccc", 8.8, -9) >>> table.print() +---------------+---------------------------+----------+ | col1 | column 2 has a big header | column 3 | +---------------+---------------------------+----------+ | aaaaaaaaa | 2.2 | 3 | | bbbbbbbbbbbbb | -5.5 | 6 | | ccccccc | 8.8 | -9 | +---------------+---------------------------+----------+
Sorting tables
- class ansitable.ANSITable(*pos, colsep=1, offset=0, border=None, bordercolor=None, ellipsis=True, columns=None, header=True, color=True)[source]
Bases:
object- sort(column, key=None, reverse=False)[source]
Sort the table rows by a column, in place
- Parameters:
column (str | int) – column to sort by, either the column name or its zero-based index
key (Callable[[str], Any] | None) – callable applied to each formatted cell value before comparison, defaults to None (lexicographic order on the formatted string)
reverse (bool) – sort in descending order, defaults to False
- Raises:
ValueError – if
columnis a string that does not match any column nameIndexError – if
columnis an integer index out of range
- Return type:
ANSITable
- Returns:
the table, to allow chaining
Rows inserted with
rule()(horizontal rules) are silently dropped from the sorted output, as they have no meaningful position after reordering.Example:
>>> from ansitable import ANSITable >>> table = ANSITable("name", "score") >>> table.row("alice", 3) >>> table.row("bob", 1) >>> table.row("carol", 2) >>> table.sort("score", key=int) ANSITable: 3 x 2: name; score >>> table.print() name score bob 1 carol 2 alice 3
Render in markup formats
These methods are used to export an ANSI table to different markup languages.
- class ansitable.table.ANSITable(*pos, colsep=1, offset=0, border=None, bordercolor=None, ellipsis=True, columns=None, header=True, color=True)[source]
Bases:
object- markdown()[source]
Output the table in MarkDown markup format
- Return type:
- Returns:
ASCII markdown text
Example:
>>> from ansitable import ANSITable >>> table = ANSITable("col1", "column 2 has a big header", "column 3") >>> table.row("aaaaaaaaa", 2.2, 3) >>> table.row("bbbbbbbbbbbbb", -5.5, 6) >>> table.row("ccccccc", 8.8, -9) >>> print(table.markdown()) | col1 | column 2 has a big header | column 3 | | ------------: | ------------------------: | -------: | | aaaaaaaaa | 2.2 | 3 | | bbbbbbbbbbbbb | -5.5 | 6 | | ccccccc | 8.8 | -9 |
This can be used inside a Jupyter notebook cell to display a table:
from IPython.display import Markdown Markdown(table.markdown())
Note
supports column alignment
does not support header alignment, same as column
rows added with
rule()are omitted from the output
- rest()[source]
Output the table in ReST “simple table” markup format
- Return type:
- Returns:
ASCII text for a ReST “simple table”
Example:
>>> from ansitable import ANSITable >>> table = ANSITable("col1", "column 2 has a big header", "column 3") >>> table.row("aaaaaaaaa", 2.2, 3) >>> table.row("bbbbbbbbbbbbb", -5.5, 6) >>> table.row("ccccccc", 8.8, -9) >>> print(table.rest()) ============= ========================= ======== col1 column 2 has a big header column 3 ============= ========================= ======== aaaaaaaaa 2.2 3 bbbbbbbbbbbbb -5.5 6 ccccccc 8.8 -9 ============= ========================= ========
Note
does not support header or column alignment
rows added with
rule()are omitted from the output
- wikitable()[source]
Output the table in wikitable markup format
This is the markup format for tables in Wikipedia.
- Return type:
- Returns:
wikitable markup text
Example:
>>> from ansitable import ANSITable >>> table = ANSITable("col1", "column 2 has a big header", "column 3") >>> table.row("aaaaaaaaa", 2.2, 3) >>> table.row("bbbbbbbbbbbbb", -5.5, 6) >>> table.row("ccccccc", 8.8, -9) >>> print(table.wikitable()) {| class="wikitable" col1right col2right col3right |- ! col1 !! column 2 has a big header !! column 3 |- | aaaaaaaaa || 2.2 || 3 |- | bbbbbbbbbbbbb || -5.5 || 6 |- | ccccccc || 8.8 || -9 |}
Note
supports column alignment
does not support header alignment, always centred for
wikitableclassrows added with
rule()are omitted from the output
- html(td='', th='', trd='', trh='', table='')[source]
Output the table in HTML format
- Parameters:
- Return type:
- Returns:
table rendered in HTML
The table is rendered as a table between
<table>and</table>tags. Table color and style options are supported.Example:
>>> from ansitable import ANSITable >>> table = ANSITable("col1", "column 2 has a big header", "column 3") >>> table.row("aaaaaaaaa", 2.2, 3) >>> table.row("bbbbbbbbbbbbb", -5.5, 6) >>> table.row("ccccccc", 8.8, -9) >>> print(table.html()) <table> <tr style=''> <th style='text-align:right;'>col1</th> <th style='text-align:right;'>column 2 has a big header</th> <th style='text-align:right;'>column 3</th> </tr> <tr style=''> <td style='text-align:right;'>aaaaaaaaa</td> <td style='text-align:right;'>2.2</td> <td style='text-align:right;'>3</td> </tr> <tr style=''> <td style='text-align:right;'>bbbbbbbbbbbbb</td> <td style='text-align:right;'>-5.5</td> <td style='text-align:right;'>6</td> </tr> <tr style=''> <td style='text-align:right;'>ccccccc</td> <td style='text-align:right;'>8.8</td> <td style='text-align:right;'>-9</td> </tr> </table>
CSS options defined in the document will apply. These can be overridden for various table elements by passed arguments strings. For example, to create a simple gridded table:
table.html( td="border: 1px solid;", th="border: 1px solid;", table="border-collapse: collapse;", )
The CSS style strings must end with a semi-colon.
Note
supports column alignment
supports header alignment
support color and style options in the table
rows added with
rule()are rendered as a<hr>spanning all columns
- latex()[source]
Output the table in LaTeX format
- Return type:
- Returns:
LaTeX tabular markup
Example:
>>> from ansitable import ANSITable >>> table = ANSITable("col1", "column 2 has a big header", "column 3") >>> table.row("aaaaaaaaa", 2.2, 3) >>> table.row("bbbbbbbbbbbbb", -5.5, 6) >>> table.row("ccccccc", 8.8, -9) >>> print(table.latex()) \begin{tabular}{ |r|r|r| }\hline \multicolumn{1}{|r|}{col1} & \multicolumn{1}{|r|}{column 2 has a big header} & \multicolumn{1}{|r|}{column 3}\\\hline\hline aaaaaaaaa & 2.2 & 3 \\ bbbbbbbbbbbbb & -5.5 & 6 \\ ccccccc & 8.8 & -9 \\ \hline \end{tabular}
Note
supports column alignment
supports header alignment
rows added with
rule()are rendered as\\hline
- csv(delimiter=',')[source]
Output the table in comma separated column (CSV) format
- Parameters:
delimiter (
str) – column delimiter, defaults to “,”- Return type:
- Returns:
ASCII CSV text
Example:
>>> from ansitable import ANSITable >>> table = ANSITable("col1", "column 2 has a big header", "column 3") >>> table.row("aaaaaaaaa", 2.2, 3) >>> table.row("bbbbbbbbbbbbb", -5.5, 6) >>> table.row("ccccccc", 8.8, -9) >>> print(table.csv()) col1,column 2 has a big header,column 3 aaaaaaaaa,2.2,3 bbbbbbbbbbbbb,-5.5,6 ccccccc,8.8,-9
Note
does not support header or column alignment
rows added with
rule()are omitted from the output
- pandas(underscores=True)[source]
Convert the table to a Pandas dataframe
- Parameters:
underscores (
bool) – replace spaces in column names with underscores, defaults to True- Return type:
DataFrame- Returns:
Pandas dataframe
Example:
>>> from ansitable import ANSITable >>> table = ANSITable("col1", "column 2 has a big header", "column 3") >>> table.row("aaaaaaaaa", 2.2, 3) >>> table.row("bbbbbbbbbbbbb", -5.5, 6) >>> table.row("ccccccc", 8.8, -9) >>> df = table.pandas() >>> print(df) col1 column_2_has_a_big_header column_3 0 aaaaaaaaa 2.2 3 1 bbbbbbbbbbbbb -5.5 6 2 ccccccc 8.8 -9
Note
does not support header or column alignment
ANSItable column headings can contain spaces, but Pandas column names with spaces cannot be used as attributes. By default spaces are replaced with underscores, but this can be disabled by passing
underscores=False.rows added with
rule()are omitted from the output