Python tabulate module: How to Easily Create Tables in Python?

tables in Python tabulate module

In this tutorial, you are going to explore how to create tables in Python, a necessary skill in the realm of data science, with the help of the tabulate function. We’ll also learned about the different properties involved with creating tables.

Python tabulate makes creating and formatting tables easy and efficient. Start by importing the module. You can then create a table by storing your data in a nested list and passing it to the tabulate function. To enhance the look of your table, use the tablefmt attribute and set it to grid for a bordered table, or fancy_grid for a more sophisticated border. If you need the HTML code, set tablefmt to ‘html’.

Also read: How to Render a Data Frame to a LaTeX Table?

Step-by-Step Guide to Creating Tables with Python’s Tabulate Module

Without any further ado, let’s get right into the steps to create tables in Python with the use of the tabulate module.

Step 1: Setting the Stage – Importing Tabulate

Firstly, we need to import the tabulate function from the tabulate library, a Python package widely used in data science and machine learning projects. In case this results in an error make sure you have the tabulate library installed by executing the pip install command on the command prompt.

from tabulate import tabulate

Now let’s create our very first table with the help of the tabulate function. In data science, it’s often necessary to organize large quantities of data in a structured, readable format – that’s where Python tabulate comes handy.

Step 2: Building the Basics – Creating Simple Tables

The data of the table is stored in the form of nested lists as shown in the code mentioned below.

all_data = [["Roll Number","Student name","Marks"],
            [1,"Sasha",34],
            [2,"Richard",36],
            [3,"Judy",20],
            [4,"Lori",39],
            [5,"Maggie",40]]

To tabulate the data, we just pass the data to the tabulate function. We can also make the first nested list as the head of the table by using an attribute known as headers.

table1 = tabulate(all_data)
table2 = tabulate(all_data,headers='firstrow')

print(table1)
print(table2)

The results of both the tables are shown below.

-----------  ------------  -----
Roll Number  Student name  Marks
1            Sasha         34
2            Richard       36
3            Judy          20
4            Lori          39
5            Maggie        40
-----------  ------------  -----
Roll Number  Student name      Marks
-------------  --------------  -------
            1  Sasha                34
            2  Richard              36
            3  Judy                 20
            4  Lori                 39
            5  Maggie               40

The presentation of data is just as important as the analysis. By neatly aligning columns and adding borders, we ensure our tables are not only readable but also pleasing to the eye.

Step 3: Amplifying the Aesthetics – Formatting Your Python Table

To make tables in Python look better, we can add borders for the table to make it look more tabular instead of textual data. The borders can be added with the help of the tablefmt attribute and set its value to grid.

print(tabulate(all_data,headers='firstrow',tablefmt='grid'))
+---------------+----------------+---------+
|   Roll Number | Student name   |   Marks |
+===============+================+=========+
|             1 | Sasha          |      34 |
+---------------+----------------+---------+
|             2 | Richard        |      36 |
+---------------+----------------+---------+
|             3 | Judy           |      20 |
+---------------+----------------+---------+
|             4 | Lori           |      39 |
+---------------+----------------+---------+
|             5 | Maggie         |      40 |
+---------------+----------------+---------+

To make it look better, we can use fancy_grid instead of a simple grid. In Python’s tabulate, ‘fancy_grid’ offers a nicely formatted and visually appealing output, suitable for presenting complex data in a clear, digestible manner.

print(tabulate(all_data,headers='firstrow',tablefmt='fancy_grid'))
╒═══════════════╤════════════════╤═════════╕
│   Roll Number │ Student name   │   Marks │
╞═══════════════╪════════════════╪═════════╡
│             1 │ Sasha          │      34 │
├───────────────┼────────────────┼─────────┤
│             2 │ Richard        │      36 │
├───────────────┼────────────────┼─────────┤
│             3 │ Judy           │      20 │
├───────────────┼────────────────┼─────────┤
│             4 │ Lori           │      39 │
├───────────────┼────────────────┼─────────┤
│             5 │ Maggie         │      40 │
╘═══════════════╧════════════════╧═════════╛

Step 4: The Web Twist – Extracting HTML Code from Tabulate

To extract the HTML code of the table, we need to set the tablefmt attribute to html. The same is displayed below.

print(tabulate(all_data,headers='firstrow',tablefmt='html'))
<table>
<thead>
<tr><th style="text-align: right;">  Roll Number</th><th>Student name  </th><th style="text-align: right;">  Marks</th></tr>
</thead>
<tbody>
<tr><td style="text-align: right;">            1</td><td>Sasha         </td><td style="text-align: right;">     34</td></tr>
<tr><td style="text-align: right;">            2</td><td>Richard       </td><td style="text-align: right;">     36</td></tr>
<tr><td style="text-align: right;">            3</td><td>Judy          </td><td style="text-align: right;">     20</td></tr>
<tr><td style="text-align: right;">            4</td><td>Lori          </td><td style="text-align: right;">     39</td></tr>
<tr><td style="text-align: right;">            5</td><td>Maggie        </td><td style="text-align: right;">     40</td></tr>
</tbody>
</table>

Getting the HTML code from tabulate provides a gateway to integrate your data with web applications, further extending its use in data science.

Also read: Pandas build_table_schema – Create a Table schema from data.

Wrapping Up: Power of Tabulate in Python

In this tutorial, we created our own tabular data using the tabulate function and also learned about some properties of the tables. Python libraries like tabulate and prettytable not only make data manipulation easy but also enhance the readability of your output. Whether you’re working on machine learning projects or diving deep into data analysis, mastering these tools can help elevate your work.

Reference: tabulate – (pyneng.readthedocs.io)