13
The easiest way to create tables in Python is to use tablulate() function from the tabulate library.
To use this function, we must first install the library using pip:
pip install tabulate
We can then load the library:
from tabulate import tabulate
We can then use the following basic syntax to create tables:
print(tabulate(data, headers=col_names, tablefmt="grid", showindex="always"))
The following examples show how to use this function in practice.
Example 1: Create Table with Headers
The following code shows how to create a basic table with headers:
#create data
data = [["Mavs", 99],
["Suns", 91],
["Spurs", 94],
["Nets", 88]]
#define header names
col_names = ["Team", "Points"]
#display table
print(tabulate(data, headers=col_names))
Team Points
------ --------
Mavs 99
Suns 91
Spurs 94
Nets 88
Example 2: Create Table with Fancy Grid
The following code shows how to create a table with headers and a fancy grid:
#create data
data = [["Mavs", 99],
["Suns", 91],
["Spurs", 94],
["Nets", 88]]
#define header names
col_names = ["Team", "Points"]
#display table
print(tabulate(data, headers=col_names, tablefmt="fancy_grid"))
╒════════╤══════════╕
│ Team │ Points │
╞════════╪══════════╡
│ Mavs │ 99 │
├────────┼──────────┤
│ Suns │ 91 │
├────────┼──────────┤
│ Spurs │ 94 │
├────────┼──────────┤
│ Nets │ 88 │
╘════════╧══════════╛
Note that the tablefmt argument accepts several different options including:
- grid
- fancy_grid
- pipe
- pretty
- simple
Refer to the tabulate documentation for a complete list of potential table formats.
Example 3: Create Table with Index Column
The following code shows how to create a table with headers, a fancy grid, and an index column:
#create data
data = [["Mavs", 99],
["Suns", 91],
["Spurs", 94],
["Nets", 88]]
#define header names
col_names = ["Team", "Points"]
#display table
print(tabulate(data, headers=col_names, tablefmt="fancy_grid", showindex="always"))
╒════╤════════╤══════════╕
│ │ Team │ Points │
╞════╪════════╪══════════╡
│ 0 │ Mavs │ 99 │
├────┼────────┼──────────┤
│ 1 │ Suns │ 91 │
├────┼────────┼──────────┤
│ 2 │ Spurs │ 94 │
├────┼────────┼──────────┤
│ 3 │ Nets │ 88 │
╘════╧════════╧══════════╛