Creating an output table in Python using PTable is fast and easy. This article introduces the most useful functionalities of PTable, such as adding rows and columns, changing text alignment and floating number format, and clearing data, to get a quick start to make the ideal table in no time.
If this is not enough, here are two detailed tutorials of PTable: http://zetcode.com/python/prettytable/ and https://github.com/jazzband/prettytable
Install PTable in Terminal
pip install ptable
Install PTable in Jupyter kernel
import sys !{sys.executable} -m pip install ptable
Create an empty table
### Import the package from prettytable import PrettyTable
### Create a table table = PrettyTable() print(table) # print an empty table
++ || ++ ++
Edit table by row
table.field_names = ['column1', 'column2'] # add column names print(table)
+---------+---------+ | column1 | column2 | +---------+---------+ +---------+---------+
table.add_row([11, 12]) # add a row table.add_row([21, 22]) # add another row print(table)
+---------+---------+ | column1 | column2 | +---------+---------+ | 11 | 12 | | 21 | 22 | +---------+---------+
table.del_row(1) # delete the row with index 1 print(table)
+---------+---------+ | column1 | column2 | +---------+---------+ | 11 | 12 | +---------+---------+
Edit table by column
table.add_column('column3', [31.0]) # add a new column print(table)
+---------+---------+---------+ | column1 | column2 | column3 | +---------+---------+---------+ | 11 | 12 | 31.0 | +---------+---------+---------+
Text alignment
table.align['column1'] = 'l' # 'l', 'c', or 'r' table.align['column2'] = 'c' table.align['column3'] = 'r' print(table)
+---------+---------+---------+ | column1 | column2 | column3 | +---------+---------+---------+ | 11 | 12 | 31.0 | +---------+---------+---------+
Floating number format
table.float_format['column3'] = "8.4" # This is equivalent to '%8.4f' % column_value print(table)
+---------+---------+----------+ | column1 | column2 | column3 | +---------+---------+----------+ | 11 | 12 | 31.0000 | +---------+---------+----------+
Add title
print(table.get_string(title="Table Title"))
+------------------------------+ | Table title | +---------+---------+----------+ | column1 | column2 | column3 | +---------+---------+----------+ | 11 | 12 | 31.0000 | +---------+---------+----------+
Clear data
table.clear_rows() print(table)
+---------+---------+---------+ | column1 | column2 | column3 | +---------+---------+---------+ +---------+---------+---------+