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, optional) – Blank padding on each side of column separator, defaults to 1
offset (int, optional) – Horizontal offset of the whole table, defaults to 0
border (str, optional) – Type of border, defaults to None
bordercolor (str, optional) – Name of color to draw border in, defaults to None
ellipsis (bool, optional) – truncated lines are shown with an ellipsis, defaults to True
columns (list of
Column
objects, optional) – specify detailed column format options, defaults to Noneheader (bool, optional) – Show table header, defaults to True
color (bool, optional) – [description], defaults to True
- Raises:
TypeError – [description]
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.addcolumnColumn("col1"), table.addcolumnColumn("column 2 has a big header", "{:.3g}"), table.addcolumnColumn("column 3", "{:-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
thin+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
- Parameters:
name (str) – column heading
An alternative way to create a table, column at a time.
Example:
table = ANSITable() table.addcolumnColumn("col1"), table.addcolumnColumn("column 2 has a big header", "{:.3g}"), table.addcolumnColumn("column 3", "{:-10.4f}")
Note
Additional arguments are passed directly to
Column
.
- static Pandas(df, **kwargs)[source]
Create an ANSITable from a Pandas dataframe
- Parameters:
df (
pandas.DataFrame
) – Pandas dataframekwargs – additional arguments to pass to the ANSITable constructor
- Returns:
an ansitable object
- Return type:
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, optional) – Python format string, defaults to “{}”
width (int, optional) – Column width, defaults to auto-fit
colcolor (str, optional) – Color of column text, defaults to None
colbgcolor (str, optional) – Color of column background, defaults to None
colstyle (str, optional) – Column text style, see table below, defaults to None
colalign (str, optional) – Column data alignement, see table below, defaults to “>”
headcolor (str, optional) – Color of heading text, defaults to None
headbgcolor (str, optional) – Color of heading background, defaults to None
headstyle (str, optional) – Heading text style, see table below, defaults to None
headalign (str, optional) – Heading text alignement, see table below, defaults to “>”
The
Column
object can passed to theANSITable
constructor 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.
- 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:
This class is used to override the color and style of a cell in a table, for example:
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()
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.
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
- Param:
values: 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. TheCell
encapsulates a value and allows the color or style defaults of the row or column to be overriden.- Parameters:
- Raises:
ValueError – invalid format string for the data provided
table.row(d1, d2, ... dN)
add data items that comprise a row of the table.N
is 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
Column
was created, but it can be overridden for a specific row by specifying the optionsfgcolor
,bgcolor
, orstyle
.Cell
overrides the color and style of a cell specified for a column and a row.
- rule()[source]
Add a horizontal rule to the table
This is a horizontal line across all columns, used to delineate parts of the table.
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 (writeable object, optional) – Print the table to this file, defaults to stdout
Example:
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) table.print() +--------------+---------------------------+----------+ | col1 | column 2 has a big header | column 3 | +--------------+---------------------------+----------+ | aaaaaaaaa | 2.2 | 3 | |bbbbbbbbbbbbb | -5.5 | 6 | | ccccccc | 8.8 | -9 | +--------------+---------------------------+----------+
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
- Returns:
ASCII markdown text
- Return type:
Example:
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) table.markdown() | 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, same as column
- rest()[source]
Output the table in ReST “simple table” markup format
- Returns:
ASCII text for a ReST “simple table”
- Return type:
Example:
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) 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
- wikitable()[source]
Output the table in wikitable markup format
This is the markup format for tables in Wikipedia.
- Returns:
ASCII markdown text
- Return type:
Example:
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) 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
wikitable
class
- html(td='', th='', trd='', trh='', table='')[source]
Output the table in HTML format
- Parameters:
td (str, optional) – CSS style for table data cells, defaults to “”
th (str, optional) – CSSstyle for table header cells, defaults to “”
trd (str, optional) – CSS style for table data rows, defaults to “”
trh (str, optional) – CSS style for table header rows, defaults to “”
table (str, optional) – CSS style for the table, defaults to “”
- Returns:
table rendered in HTML
- Return type:
The table is rendered as a table between <table> and </table> tags. Table color and style options are supported.
Example:
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) table.html() <table> <tr> <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> <td style='text-align:right;'>aaaaaaaaa</td> <td style='text-align:right;'>2.2</td> <td style='text-align:right;'>3</td> </tr> <tr> <td style='text-align:right;'>bbbbbbbbbbbbb</td> <td style='text-align:right;'>-5.5</td> <td style='text-align:right;'>6</td> </tr> <tr> <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
- latex()[source]
Output the table in LaTeX format
- Returns:
ASCII markdown text
- Return type:
Example:
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) 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
- csv(delimiter=',')[source]
Output the table in comma separated column (CSV) format
- Parameters:
delimiter (str, optional) – column delimiter, defaults to “,”
- Returns:
ASCII CSV text
- Return type:
Example:
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) 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
- pandas(underscores=True)[source]
Convert the table to a Pandas dataframe
- Parameters:
underscores (bool, optional) – replace spaces in column names with underscores, defaults to True
- Returns:
Pandas dataframe
- Return type:
DataFrame object
Example:
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
.