Python Library – Tabulate

Introduction to Tabulate

Python is one of the most popular programming language and is widely used by programmers. It’s syntax are easy to understand which makes it beginner’s first choice.

it also contains a large number of libraries which can be directly imported and used in our program (for example, Pandas, Numpy, Matplotlib). One of such libraries is Tabulate which is specifically used for creating well structured tables in python.

In this blog you will get to know about tabulate library, its use , examples and its practical life use cases.

What is Tablulate?

The tabulate library in Python is a powerful tool for creating formatted tables from various data sources. It offers an easy and efficient way to display data in a well-structured, readable format, which is particularly useful for data scientists, analysts, and developers.

It provides various options of table to keep your data organised as per your usage.

Key Uses of tabulate

  1. Displaying Structured Data
  • Converts lists, dictionaries, and pandas DataFrames into well-formatted tables.
  • Ideal for logging, debugging, and presenting results in a readable format.
  1. Generating Reports
  • Helps in creating clean tables for console output.
  • Supports exporting tables in various formats like Markdown, HTML, and LaTeX for documentation or presentations.
  1. Integrating with Data Processing Libraries
  • Works well with pandas, allowing DataFrame tables to be displayed with custom formatting.

Utility & Features

1. Supports Multiple Table Formats

  • Styles include fancy_grid, plain, pipe, html, latex, etc.

2. Customizable Headers & Indices

  • Allows adding headers, row indices, and column alignments.

3. Lightweight & Easy to Use

  • Requires minimal setup and works efficiently for quick tabular displays.

4. Markdown & HTML Support

  • Ideal for generating tables in blogs, reports, and documentation.

Till now you must have known how useful tabulate library is in python.

Lets learn about Tabulate from basic- installation, setup, types of data, uses etc.

Installation and setup

To install Tabulate library in windows, open your command prompt window and run the following code.Screenshot 2025-02-24 213528.png You can see it is installed and ready to use!

As I am currently working in Google Colab notebook i will install it using same command.

pip install tabulate
Requirement already satisfied: tabulate in /usr/local/lib/python3.11/dist-packages (0.9.0)

you can see it is already there so lets now start playing with function of this library!!

The following code snippet demonstrates how to format and display tabular data using Python:

 from tabulate import tabulate
table = [["boy1",72,175,"Gujarat"],["boy2",53,183,"Maharashtra"],["boy3",80,173,"Telangana"],["boy4",65,160,"Rajasthan"]]
print(tabulate(table))
----  --  ---  -----------
boy1  72  175  Gujarat
boy2  53  183  Maharashtra
boy3  80  173  Telangana
boy4  65  160  Rajasthan
----  --  ---  -----------

Headers

We can use Headers argument to add headings to the columns of our table.

head = ["Name","Weight","Height","State"]
print(tabulate(table,headers=head))
Name      Weight    Height  State
------  --------  --------  -----------
boy1          72       175  Gujarat
boy2          53       183  Maharashtra
boy3          80       173  Telangana
boy4          65       160  Rajasthan

If we wish to have the first row itself as the header, we can use headers=“firstrow”

print(tabulate(table,headers="firstrow"))
boy1      72    175  Gujarat
------  ----  -----  -----------
boy2      53    183  Maharashtra
boy3      80    173  Telangana
boy4      65    160  Rajasthan

If we have a dictionary or a dataframe and we want the keys to be the header, we can use headers=“keys”.

print(tabulate({"Colours":["Blue","Green","Red"],
                "Count":["23","42","36"],
                "object":["ball","pencil","pens"]},
               headers="keys"))
Colours      Count  object
---------  -------  --------
Blue            23  ball
Green           42  pencil
Red             36  pens

Row Indices

To add a column showing the indices, we use showindex=“always” or showindex=True argument to tabulate()

print(tabulate(table,headers=head, showindex="always"))  # we are continuing the same dataset and by modifying it we can see difference.
    Name      Weight    Height  State
--  ------  --------  --------  -----------
 0  boy1          72       175  Gujarat
 1  boy2          53       183  Maharashtra
 2  boy3          80       173  Telangana
 3  boy4          65       160  Rajasthan

Table format

There are multiple ways in which a table can be layed out in plain text. We use tablefmt to format a table.

A few examples are listed below

1.Plain

As the name suggests it is plain and does not have anny line.

table = [["boy1",72,175,"Gujarat"],["boy2",53,183,"Maharashtra"],["boy3",80,173,"Telangana"],["boy4",65,160,"Rajasthan"]]
print(tabulate(table,headers=head,tablefmt="plain"))
Name      Weight    Height  State
boy1          72       175  Gujarat
boy2          53       183  Maharashtra
boy3          80       173  Telangana
boy4          65       160  Rajasthan

2. Simple

It is default type of table if table formate is not specified it will be simple.

print(tabulate(table,headers=head,tablefmt="simple"))
Name      Weight    Height  State
------  --------  --------  -----------
boy1          72       175  Gujarat
boy2          53       183  Maharashtra
boy3          80       173  Telangana
boy4          65       160  Rajasthan

3.Grid

A table format that adds borders around each cell for a clear and organized display of data.

print(tabulate(table,headers=head,tablefmt="grid"))
+--------+----------+----------+-------------+
| Name   |   Weight |   Height | State       |
+========+==========+==========+=============+
| boy1   |       72 |      175 | Gujarat     |
+--------+----------+----------+-------------+
| boy2   |       53 |      183 | Maharashtra |
+--------+----------+----------+-------------+
| boy3   |       80 |      173 | Telangana   |
+--------+----------+----------+-------------+
| boy4   |       65 |      160 | Rajasthan   |
+--------+----------+----------+-------------+

lineabove=Line(“+”, “-”, “+”, “+”),

linebelowheader=Line(“+”, “=”, “+”, “+”),

linebetweenrows=Line(“+”, “-”, “+”, “+”),

linebelow=Line(“+”, “-”, “+”, “+”),

headerrow=DataRow(“|”, “|”, “|”),

datarow=DataRow(“|”, “|”, “|”),

padding=1,

with_header_hide=

this is the default what grid function plots graph with

3.1 Simple_grid

The “simple_grid” format in the tabulate library creates a table with hyphens (-) for horizontal lines and spaces for column separation, offering a clean and readable output.

print(tabulate(table,headers=head,tablefmt="simple_grid"))
┌────────┬──────────┬──────────┬─────────────┐
│ Name   │   Weight │   Height │ State       │
├────────┼──────────┼──────────┼─────────────┤
│ boy1   │       72 │      175 │ Gujarat     │
├────────┼──────────┼──────────┼─────────────┤
│ boy2   │       53 │      183 │ Maharashtra │
├────────┼──────────┼──────────┼─────────────┤
│ boy3   │       80 │      173 │ Telangana   │
├────────┼──────────┼──────────┼─────────────┤
│ boy4   │       65 │      160 │ Rajasthan   │
└────────┴──────────┴──────────┴─────────────┘

3.2 Rounded_grid

rounded_grid (it is a simple grid with rounded corners)

print(tabulate(table,headers=head,tablefmt="rounded_grid"))
╭────────┬──────────┬──────────┬─────────────╮
│ Name   │   Weight │   Height │ State       │
├────────┼──────────┼──────────┼─────────────┤
│ boy1   │       72 │      175 │ Gujarat     │
├────────┼──────────┼──────────┼─────────────┤
│ boy2   │       53 │      183 │ Maharashtra │
├────────┼──────────┼──────────┼─────────────┤
│ boy3   │       80 │      173 │ Telangana   │
├────────┼──────────┼──────────┼─────────────┤
│ boy4   │       65 │      160 │ Rajasthan   │
╰────────┴──────────┴──────────┴─────────────╯

3.3 Heavy_grid

uses bold lines

print(tabulate(table,headers=head,tablefmt="heavy_grid"))
┏━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ Name   ┃   Weight ┃   Height ┃ State       ┃
┣━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━━━━┫
┃ boy1   ┃       72 ┃      175 ┃ Gujarat     ┃
┣━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━━━━┫
┃ boy2   ┃       53 ┃      183 ┃ Maharashtra ┃
┣━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━━━━┫
┃ boy3   ┃       80 ┃      173 ┃ Telangana   ┃
┣━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━━━━┫
┃ boy4   ┃       65 ┃      160 ┃ Rajasthan   ┃
┗━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━━━━━┛

3.4 Mixed_grid

uses a mix of both thin and bold lines

print(tabulate(table,headers=head,tablefmt="mixed_grid"))
┍━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━━┑
│ Name   │   Weight │   Height │ State       │
┝━━━━━━━━┿━━━━━━━━━━┿━━━━━━━━━━┿━━━━━━━━━━━━━┥
│ boy1   │       72 │      175 │ Gujarat     │
├────────┼──────────┼──────────┼─────────────┤
│ boy2   │       53 │      183 │ Maharashtra │
├────────┼──────────┼──────────┼─────────────┤
│ boy3   │       80 │      173 │ Telangana   │
├────────┼──────────┼──────────┼─────────────┤
│ boy4   │       65 │      160 │ Rajasthan   │
┕━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━┙

3.5 Double_grid

Uses double lines

print(tabulate(table,headers=head,tablefmt="double_grid"))
╔════════╦══════════╦══════════╦═════════════╗
║ Name   ║   Weight ║   Height ║ State       ║
╠════════╬══════════╬══════════╬═════════════╣
║ boy1   ║       72 ║      175 ║ Gujarat     ║
╠════════╬══════════╬══════════╬═════════════╣
║ boy2   ║       53 ║      183 ║ Maharashtra ║
╠════════╬══════════╬══════════╬═════════════╣
║ boy3   ║       80 ║      173 ║ Telangana   ║
╠════════╬══════════╬══════════╬═════════════╣
║ boy4   ║       65 ║      160 ║ Rajasthan   ║
╚════════╩══════════╩══════════╩═════════════╝

3.6 Fancy_grid

Uses a mix of single and double lines

print(tabulate(table,headers=head,tablefmt="fancy_grid"))
╒════════╤══════════╤══════════╤═════════════╕
│ Name   │   Weight │   Height │ State       │
╞════════╪══════════╪══════════╪═════════════╡
│ boy1   │       72 │      175 │ Gujarat     │
├────────┼──────────┼──────────┼─────────────┤
│ boy2   │       53 │      183 │ Maharashtra │
├────────┼──────────┼──────────┼─────────────┤
│ boy3   │       80 │      173 │ Telangana   │
├────────┼──────────┼──────────┼─────────────┤
│ boy4   │       65 │      160 │ Rajasthan   │
╘════════╧══════════╧══════════╧═════════════╛

4. Github

generates tables in Markdown style, making it ideal for documentation and README files.

print(tabulate(table,headers=head,tablefmt="github"))
| Name   |   Weight |   Height | State       |
|--------|----------|----------|-------------|
| boy1   |       72 |      175 | Gujarat     |
| boy2   |       53 |      183 | Maharashtra |
| boy3   |       80 |      173 | Telangana   |
| boy4   |       65 |      160 | Rajasthan   |

5. Outline

it is same as Grid the only difference between them is, in outline there are no lines present between two rows and in Grid there are lines between rows.

example of outline are:

print(tabulate(table,headers=head,tablefmt="outline"))
# you can see here no line between rows.
+--------+----------+----------+-------------+
| Name   |   Weight |   Height | State       |
+========+==========+==========+=============+
| boy1   |       72 |      175 | Gujarat     |
| boy2   |       53 |      183 | Maharashtra |
| boy3   |       80 |      173 | Telangana   |
| boy4   |       65 |      160 | Rajasthan   |
+--------+----------+----------+-------------+

All other outline_simple stc. are same as grid_simple etc. without lines between rows.

6. Presto

The presto table format in tabulate mimics the output style of the Presto SQL command-line interface, displaying clean, grid-like tables.

print(tabulate(table,headers=head,tablefmt="presto"))
 Name   |   Weight |   Height | State
--------+----------+----------+-------------
 boy1   |       72 |      175 | Gujarat
 boy2   |       53 |      183 | Maharashtra
 boy3   |       80 |      173 | Telangana
 boy4   |       65 |      160 | Rajasthan

7. Psql

The psql table format in tabulate mimics the output style of PostgreSQL, displaying tables with aligned columns and borders for better readability in SQL-like environments.

print(tabulate(table,headers=head,tablefmt="psql"))
+--------+----------+----------+-------------+
| Name   |   Weight |   Height | State       |
|--------+----------+----------+-------------|
| boy1   |       72 |      175 | Gujarat     |
| boy2   |       53 |      183 | Maharashtra |
| boy3   |       80 |      173 | Telangana   |
| boy4   |       65 |      160 | Rajasthan   |
+--------+----------+----------+-------------+

8. Pipe

Uses “|” characters to separate columns, creating a simple and clean table format.

print(tabulate(table,headers=head,tablefmt="pipe"))
| Name   |   Weight |   Height | State       |
|:-------|---------:|---------:|:------------|
| boy1   |       72 |      175 | Gujarat     |
| boy2   |       53 |      183 | Maharashtra |
| boy3   |       80 |      173 | Telangana   |
| boy4   |       65 |      160 | Rajasthan   |

9. Asciidoc

The asciidoc function in tabulate formats tables as AsciiDoc-style markup, making them suitable for documentation and publishing.

print(tabulate(table,headers=head,tablefmt="asciidoc"))
[cols="8<,10>,10>,13<",options="header"]
|====
| Name   |   Weight |   Height | State       
| boy1   |       72 |      175 | Gujarat     
| boy2   |       53 |      183 | Maharashtra 
| boy3   |       80 |      173 | Telangana   
| boy4   |       65 |      160 | Rajasthan   
|====

10. Orgtbl

The orgtbl function in tabulate formats tables in Org-mode style, commonly used in Emacs for structured text and data organization.

print(tabulate(table,headers=head,tablefmt="orgtbl"))
| Name   |   Weight |   Height | State       |
|--------+----------+----------+-------------|
| boy1   |       72 |      175 | Gujarat     |
| boy2   |       53 |      183 | Maharashtra |
| boy3   |       80 |      173 | Telangana   |
| boy4   |       65 |      160 | Rajasthan   |

11. Jira

Using pipes (|) for column separation and hyphens (-) for line breaks.

print(tabulate(table,headers=head,tablefmt="jira"))
|| Name   ||   Weight ||   Height || State       ||
| boy1   |       72 |      175 | Gujarat     |
| boy2   |       53 |      183 | Maharashtra |
| boy3   |       80 |      173 | Telangana   |
| boy4   |       65 |      160 | Rajasthan   |

12. html

The html function in tabulate converts tabular data into an HTML table format, making it easy to embed tables in web pages.

print(tabulate(table,headers=head,tablefmt="html"))
<table>
<thead>
<tr><th>Name  </th><th style="text-align: right;">  Weight</th><th style="text-align: right;">  Height</th><th>State      </th></tr>
</thead>
<tbody>
<tr><td>boy1  </td><td style="text-align: right;">      72</td><td style="text-align: right;">     175</td><td>Gujarat    </td></tr>
<tr><td>boy2  </td><td style="text-align: right;">      53</td><td style="text-align: right;">     183</td><td>Maharashtra</td></tr>
<tr><td>boy3  </td><td style="text-align: right;">      80</td><td style="text-align: right;">     173</td><td>Telangana  </td></tr>
<tr><td>boy4  </td><td style="text-align: right;">      65</td><td style="text-align: right;">     160</td><td>Rajasthan  </td></tr>
</tbody>
</table>

13. Latex

The latex function in tabulate formats tabular data into LaTeX-compatible tables for seamless integration into LaTeX documents.

print(tabulate(table,headers=head,tablefmt="latex"))
\begin{tabular}{lrrl}
\hline
 Name   &   Weight &   Height & State       \\
\hline
 boy1   &       72 &      175 & Gujarat     \\
 boy2   &       53 &      183 & Maharashtra \\
 boy3   &       80 &      173 & Telangana   \\
 boy4   &       65 &      160 & Rajasthan   \\
\hline
\end{tabular}

Column Alignment

When using Tabulate, it’s clever about aligning your columns. If a column has only numbers, it aligns them by the decimal point or to the right if they’re integers. Text columns, on the other hand, are aligned to the left.

num=[[12.34],[4.567],[8901],[234.5],[2345.234],[0.00843]]
print(tabulate(num))
----------
  12.34
   4.567
8901
 234.5
2345.23
   0.00843
----------
print(tabulate(num ,numalign='right'))
# aligns to right
print(tabulate(num ,numalign='left'))
#aligns to left
-------
  12.34
  4.567
   8901
  234.5
2345.23
0.00843
-------
-------
12.34
4.567
8901
234.5
2345.23
0.00843
-------

Tabulate has a feature in which numbers in strings are alligned properly it reads numbers written as string as integers

table_2 =[['A','23.01'],['B','35.234'],['C','42.45678']]
print(tabulate(table_2, numalign="right"))
-  -------
A    23.01
B   35.234
C  42.4568
-  -------

To not use this feature, use disable_numparse=True

print(tabulate(table_2, disable_numparse=True,numalign="right"))
-  --------
A  23.01
B  35.234
C  42.45678
-  --------

Here it reads numbers as string and does not aligns it due to numalign.

Custom column allignment

You can customize column alignment in Tabulate to fit your needs. Just use the colalign argument, which can be a list or a tuple of alignment options like right, center, left, decimal (for numbers), and None (to disable alignment).

table_3=[['apple','banana'],['camel','rat'],['toy','play']]
print(tabulate(table_3,colalign=("right")))
-----  ------
apple  banana
camel  rat
  toy  play
-----  ------
print(tabulate(table_3,colalign=("left")))
-----  ------
apple  banana
camel  rat
toy    play
-----  ------

Number formatting

You can customize the number format for all decimal columns in Tabulate using the floatfmt argument.

table_2 =[['A','23.01'],['B','35.234'],['C','42.45678']]
print(tabulate(table_2, floatfmt=".2f"))
-  -----
A  23.01
B  35.23
C  42.46
-  -----
print(tabulate(table_2, floatfmt=".3f"))
-  ------
A  23.010
B  35.234
C  42.457
-  ------

intfmt works similarly for integers

Text formatting

By default, Tabulate trims any leading or trailing whitespace from text columns. If you want to keep the whitespace, you can set the global module-level flag PRESERVE_WHITESPACE.

tabulate.PRESERVE_WHITESPACE = True

Wide (fullwidth CJK) symbols

To align tables that include wide characters (like fullwidth glyphs from Chinese, Japanese, or Korean), you should install the wcwidth library. You can install it along with Tabulate as follows:

pip install tabulate[widechars]
Requirement already satisfied: tabulate[widechars] in /usr/local/lib/python3.11/dist-packages (0.9.0)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.11/dist-packages (from tabulate[widechars]) (0.2.13)

If the wcwidth library is installed, wide character support is automatically enabled. To turn off wide character support without uninstalling wcwidth, set the global module-level flag WIDE_CHARS_MODE

tabulate.WIDE_CHARS_MODE = False

Multiline cells

Most table formats allow multiline cell text, which includes newline characters treated as line breaks.

Both data and header rows can contain multiline cells. No additional line breaks are automatically inserted; however, formats like LaTeX and HTML may handle their own formatting. For formats that don’t, newline characters in the cell text are the only method to create line breaks.

Be aware that some formats, such as simple or plain, do not show row delimiters, making multiline cells potentially unclear to the reader.

table_4 = [["cars",345],["motor\nbikes",196]]
headers_4 = ["vehicle\ntype", "count"]

1. Plain Table

print(tabulate(table_4, headers=headers_4, tablefmt="plain"))
vehicle      count
type
cars           345
motor          196
bikes

2. Simple table

print(tabulate(table_4, headers=headers_4, tablefmt="simple"))
vehicle      count
type
---------  -------
cars           345
motor          196
bikes

3. Grid Table

print(tabulate(table_4, headers=headers_4, tablefmt="grid"))
+-----------+---------+
| vehicle   |   count |
| type      |         |
+===========+=========+
| cars      |     345 |
+-----------+---------+
| motor     |     196 |
| bikes     |         |
+-----------+---------+

3.1 Fancy grid table

print(tabulate(table_4, headers=headers_4, tablefmt="fancy_grid"))
╒═══════════╤═════════╕
│ vehicle   │   count │
│ type      │         │
╞═══════════╪═════════╡
│ cars      │     345 │
├───────────┼─────────┤
│ motor     │     196 │
│ bikes     │         │
╘═══════════╧═════════╛

3.2 Pipe Table

print(tabulate(table_4, headers=headers_4, tablefmt="pipe"))
| vehicle   |   count |
| type      |         |
|:----------|--------:|
| cars      |     345 |
| motor     |     196 |
| bikes     |         |

3.3 Orgtbl tables

print(tabulate(table_4, headers=headers_4, tablefmt="orgtbl"))
| vehicle   |   count |
| type      |         |
|-----------+---------|
| cars      |     345 |
| motor     |     196 |
| bikes     |         |

3.4 Jira

print(tabulate(table_4, headers=headers_4, tablefmt="jira"))
|| vehicle   ||   count ||
|| type      ||         ||
| cars      |     345 |
| motor     |     196 |
| bikes     |         |

3.5 Pretty Table

print(tabulate(table_4, headers=headers_4, tablefmt="pretty"))
+---------+-------+
| vehicle | count |
|  type   |       |
+---------+-------+
|  cars   |  345  |
|  motor  |  196  |
|  bikes  |       |
+---------+-------+

3.6 Psql Table

print(tabulate(table_4, headers=headers_4, tablefmt="psql"))
+-----------+---------+
| vehicle   |   count |
| type      |         |
|-----------+---------|
| cars      |     345 |
| motor     |     196 |
| bikes     |         |
+-----------+---------+

3.7 Rst Table

print(tabulate(table_4, headers=headers_4, tablefmt="rst"))
=========  =======
vehicle      count
type
=========  =======
cars           345
motor          196
bikes
=========  =======

Automating Multilines

While Tabulate supports data with explicitly provided multiline entries, it also offers internal support to handle this.

The maxcolwidths argument is a list where each entry specifies the maximum width for its respective column. If a cell exceeds this width, its content will be automatically wrapped. To set the same maximum width for all columns, use a single integer value.

Use None for columns where no explicit maximum is needed, thus no automatic multiline wrapping will occur.

The wrapping process uses Python’s standard textwrap.wrap function with default parameters, except for width.

print(tabulate([["Rahul", "CEO"]], headers=["Name", "Designation"], tablefmt="grid", maxcolwidths=[None, 8]))
+--------+---------------+
| Name   | Designation   |
+========+===============+
| Rahul  | CEO           |
+--------+---------------+

Adding Separating lines

If you want to highlight different sections in a table, you can add one or more separating lines. These lines will match the type specified by the formatter. If no specific line type is defined, a simple empty line will be used.

from tabulate import tabulate, SEPARATING_LINE

table = [["A",23],
         ["B",35],
         SEPARATING_LINE,
         ["C",42]]
print(tabulate(table, tablefmt="simple"))
-  --
A  23
B  35
-  --
C  42
-  --

Practical Use Cases

  1. tabulate() – Displaying Sales Reports in CLI

Use Case: A sales manager wants to generate a quick summary of product sales.

Real-Life Application: Used in retail businesses for sales summaries.

  1. tabulate_formats() – Choosing the Best Format for a Dashboard

Use Case: A developer needs to check available table formats to pick the best one for a report.

Real-Life Application: Used by software developers and data analysts to find the best format for console applications or logs.

  1. latex() – Formatting Research Data for a Report

Use Case: A researcher needs to present structured data in a LaTeX document for publication.

Real-Life Application: Used in academic research and scientific publications.

  1. html() – Creating a Table for a Website

Use Case: A web developer wants to generate an HTML table for a product listing page.

Real-Life Application: Used in e-commerce websites to display products.

  1. TableFormat() – Creating a Custom Report Format for a Logistics Company

Use Case: A logistics company wants to customize the layout of their shipment report.

Real-Life Application: Used in logistics companies for structured reports.

Demonstration

We can use a dataset of car sales information, which includes various attributes of different car models and their sales figures. This dataset will allow us to demonstrate how tabulate can be more useful than pandas for creating tables, especially when it comes to formatting and readability.

import pandas as pd

data = {
    'Make': ['Toyota', 'Honda', 'Ford', 'Chevrolet', 'Nissan', 'BMW', 'Mercedes-Benz', 'Audi', 'Lexus', 'Hyundai'],
    'Model': ['Camry', 'Civic', 'F-150', 'Silverado', 'Altima', '3 Series', 'C-Class', 'A4', 'RX', 'Sonata'],
    'Year': [2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022],
    'Price': [25000, 22000, 35000, 32000, 24000, 45000, 50000, 42000, 48000, 23000],
    'Sales': [294348, 261225, 726004, 519774, 183183, 243277, 213708, 133964, 101059, 140979],
    'MPG_City': [28, 30, 20, 21, 28, 26, 25, 24, 31, 28],
    'MPG_Highway': [39, 38, 26, 28, 39, 36, 34, 32, 28, 38],
    'Customer_Rating': [4.5, 4.3, 4.7, 4.6, 4.2, 4.4, 4.5, 4.3, 4.6, 4.1]
}

df = pd.DataFrame(data)

First let us see how we can display table using Pandas

print(df.to_string(index=True))
            Make      Model  Year  Price   Sales  MPG_City  MPG_Highway  Customer_Rating
0         Toyota      Camry  2022  25000  294348        28           39              4.5
1          Honda      Civic  2022  22000  261225        30           38              4.3
2           Ford      F-150  2022  35000  726004        20           26              4.7
3      Chevrolet  Silverado  2022  32000  519774        21           28              4.6
4         Nissan     Altima  2022  24000  183183        28           39              4.2
5            BMW   3 Series  2022  45000  243277        26           36              4.4
6  Mercedes-Benz    C-Class  2022  50000  213708        25           34              4.5
7           Audi         A4  2022  42000  133964        24           32              4.3
8          Lexus         RX  2022  48000  101059        31           28              4.6
9        Hyundai     Sonata  2022  23000  140979        28           38              4.1

Now we will display same table using Tabulate

from tabulate import tabulate

print(tabulate(df, headers='keys', tablefmt='grid', showindex=True, floatfmt='.2f'))
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|    | Make          | Model     |   Year |   Price |   Sales |   MPG_City |   MPG_Highway |   Customer_Rating |
+====+===============+===========+========+=========+=========+============+===============+===================+
|  0 | Toyota        | Camry     |   2022 |   25000 |  294348 |         28 |            39 |              4.50 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|  1 | Honda         | Civic     |   2022 |   22000 |  261225 |         30 |            38 |              4.30 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|  2 | Ford          | F-150     |   2022 |   35000 |  726004 |         20 |            26 |              4.70 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|  3 | Chevrolet     | Silverado |   2022 |   32000 |  519774 |         21 |            28 |              4.60 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|  4 | Nissan        | Altima    |   2022 |   24000 |  183183 |         28 |            39 |              4.20 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|  5 | BMW           | 3 Series  |   2022 |   45000 |  243277 |         26 |            36 |              4.40 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|  6 | Mercedes-Benz | C-Class   |   2022 |   50000 |  213708 |         25 |            34 |              4.50 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|  7 | Audi          | A4        |   2022 |   42000 |  133964 |         24 |            32 |              4.30 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|  8 | Lexus         | RX        |   2022 |   48000 |  101059 |         31 |            28 |              4.60 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+
|  9 | Hyundai       | Sonata    |   2022 |   23000 |  140979 |         28 |            38 |              4.10 |
+----+---------------+-----------+--------+---------+---------+------------+---------------+-------------------+

Key points why Tabulate is more suitable than Pandas.

  1. Tabulate offers various table formats (e.g., ‘grid’, ‘pipe’, ‘orgtbl’, ‘rst’) that can be easily changed to suit different output needs.

  2. Tabulate automatically aligns numeric columns to the right and text columns to the left, improving readability.

  3. Tabulate allows easy control over decimal places for float values using the ‘floatfmt’ parameter.

  4. Tabulate can create ASCII art tables that are more visually appealing and easier to read in plain text environments.

  5. Tabulate can work with various data structures (lists, dictionaries, pandas DataFrames) making it versatile for different data sources.

  6. Tabulate can generate tables in Markdown and other formats, which is useful for documentation and web content.

  7. Tabulate offers better control over column widths, ensuring a more consistent look across different data types.

  8. Tables generated by tabulate are often easier to copy and paste into other applications while maintaining their structure.

Conclusion

Key takeaways

  • An introduction to Tabulate and its main features

  • Installation and setup instructions

  • Key functions like TableFormat and tabulate()

  • Customization options for headers, alignments, and table styles

  • Practical usage examples and applications

Why to use ?

Still may you have this questoin why to use Tabulate, the answer is simple, It is Versatility,have Multiple Output Formats, can do Automatic Column Alignment, Customization Options, Ease of Use, Readability.

Apart from this some major points are listed down below.

  • It works well with other data processing libraries like pandas, enhancing its utility in data analysis workflows.

  • Tabulate is useful for displaying data in command-line interfaces (CLIs), making it valuable for scripting and automation tasks.

  • It can be used to generate tables for reports and presentations, improving the visual presentation of data.

  • Tabulate works well in Jupyter Notebooks, a popular environment for data analysis and scientific computing.

Where to use?

The tabulate library is extremely useful in business, research, web development, logistics, and retail. Whether you’re displaying sales reports, creating research tables, or formatting HTML tables for a website, tabulate helps improve data presentation. Its versatility in handling different input types and output formats makes it a go-to choice for many Python projects.

Know before go

Lastly, mastering Tabulate can significantly improve your data presentation skills in Python. We encourage you to explore further and experiment with the library to unlock its full potential in your projects.

Reference and Acknowledgement

  • Tabulate Official Documentation: https://pypi.org/project/tabulate/

  • Reference blog website: https://www.pickl.ai/blog/how-to-tabulate-data-in-python/#:~:text=The%20tabulate%20module%20provides%20an,efficiently%20for%20analysis%20or%20reporting.

  • Basic youtube video to start with : https://www.youtube.com/watch?v=Yq0lbu8goeA&ab_channel=InvalidEntry

  • Our GitHub Repository for Tabulate: https://github.com/vivek-314/Exposition-Assignment-.git