pip install tabulate
Requirement already satisfied: tabulate in /usr/local/lib/python3.11/dist-packages (0.9.0)
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.
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.
Converts lists, dictionaries, and pandas DataFrames into well-formatted tables.
Lets learn about Tabulate from basic- installation, setup, types of data, uses etc.
To install Tabulate library in windows, open your command prompt window and run the following code. 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.
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:
We can use Headers argument to add headings to the columns of our table.
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”
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”.
To add a column showing the indices, we use showindex=“always” or showindex=True argument to tabulate()
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
As the name suggests it is plain and does not have anny line.
It is default type of table if table formate is not specified it will be simple.
A table format that adds borders around each cell for a clear and organized display of data.
+--------+----------+----------+-------------+
| 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
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.
┌────────┬──────────┬──────────┬─────────────┐
│ Name │ Weight │ Height │ State │
├────────┼──────────┼──────────┼─────────────┤
│ boy1 │ 72 │ 175 │ Gujarat │
├────────┼──────────┼──────────┼─────────────┤
│ boy2 │ 53 │ 183 │ Maharashtra │
├────────┼──────────┼──────────┼─────────────┤
│ boy3 │ 80 │ 173 │ Telangana │
├────────┼──────────┼──────────┼─────────────┤
│ boy4 │ 65 │ 160 │ Rajasthan │
└────────┴──────────┴──────────┴─────────────┘
rounded_grid (it is a simple grid with rounded corners)
╭────────┬──────────┬──────────┬─────────────╮
│ Name │ Weight │ Height │ State │
├────────┼──────────┼──────────┼─────────────┤
│ boy1 │ 72 │ 175 │ Gujarat │
├────────┼──────────┼──────────┼─────────────┤
│ boy2 │ 53 │ 183 │ Maharashtra │
├────────┼──────────┼──────────┼─────────────┤
│ boy3 │ 80 │ 173 │ Telangana │
├────────┼──────────┼──────────┼─────────────┤
│ boy4 │ 65 │ 160 │ Rajasthan │
╰────────┴──────────┴──────────┴─────────────╯
uses bold lines
┏━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ Name ┃ Weight ┃ Height ┃ State ┃
┣━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━━━━┫
┃ boy1 ┃ 72 ┃ 175 ┃ Gujarat ┃
┣━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━━━━┫
┃ boy2 ┃ 53 ┃ 183 ┃ Maharashtra ┃
┣━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━━━━┫
┃ boy3 ┃ 80 ┃ 173 ┃ Telangana ┃
┣━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━━━━━┫
┃ boy4 ┃ 65 ┃ 160 ┃ Rajasthan ┃
┗━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━━━━━┛
uses a mix of both thin and bold lines
┍━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━━┑
│ Name │ Weight │ Height │ State │
┝━━━━━━━━┿━━━━━━━━━━┿━━━━━━━━━━┿━━━━━━━━━━━━━┥
│ boy1 │ 72 │ 175 │ Gujarat │
├────────┼──────────┼──────────┼─────────────┤
│ boy2 │ 53 │ 183 │ Maharashtra │
├────────┼──────────┼──────────┼─────────────┤
│ boy3 │ 80 │ 173 │ Telangana │
├────────┼──────────┼──────────┼─────────────┤
│ boy4 │ 65 │ 160 │ Rajasthan │
┕━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━┙
Uses double lines
╔════════╦══════════╦══════════╦═════════════╗
║ Name ║ Weight ║ Height ║ State ║
╠════════╬══════════╬══════════╬═════════════╣
║ boy1 ║ 72 ║ 175 ║ Gujarat ║
╠════════╬══════════╬══════════╬═════════════╣
║ boy2 ║ 53 ║ 183 ║ Maharashtra ║
╠════════╬══════════╬══════════╬═════════════╣
║ boy3 ║ 80 ║ 173 ║ Telangana ║
╠════════╬══════════╬══════════╬═════════════╣
║ boy4 ║ 65 ║ 160 ║ Rajasthan ║
╚════════╩══════════╩══════════╩═════════════╝
Uses a mix of single and double lines
╒════════╤══════════╤══════════╤═════════════╕
│ Name │ Weight │ Height │ State │
╞════════╪══════════╪══════════╪═════════════╡
│ boy1 │ 72 │ 175 │ Gujarat │
├────────┼──────────┼──────────┼─────────────┤
│ boy2 │ 53 │ 183 │ Maharashtra │
├────────┼──────────┼──────────┼─────────────┤
│ boy3 │ 80 │ 173 │ Telangana │
├────────┼──────────┼──────────┼─────────────┤
│ boy4 │ 65 │ 160 │ Rajasthan │
╘════════╧══════════╧══════════╧═════════════╛
generates tables in Markdown style, making it ideal for documentation and README files.
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:
+--------+----------+----------+-------------+
| 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.
The presto table format in tabulate mimics the output style of the Presto SQL command-line interface, displaying clean, grid-like tables.
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.
+--------+----------+----------+-------------+
| Name | Weight | Height | State |
|--------+----------+----------+-------------|
| boy1 | 72 | 175 | Gujarat |
| boy2 | 53 | 183 | Maharashtra |
| boy3 | 80 | 173 | Telangana |
| boy4 | 65 | 160 | Rajasthan |
+--------+----------+----------+-------------+
Uses “|” characters to separate columns, creating a simple and clean table format.
The asciidoc function in tabulate formats tables as AsciiDoc-style markup, making them suitable for documentation and publishing.
The orgtbl function in tabulate formats tables in Org-mode style, commonly used in Emacs for structured text and data organization.
| Name | Weight | Height | State |
|--------+----------+----------+-------------|
| boy1 | 72 | 175 | Gujarat |
| boy2 | 53 | 183 | Maharashtra |
| boy3 | 80 | 173 | Telangana |
| boy4 | 65 | 160 | Rajasthan |
Using pipes (|) for column separation and hyphens (-) for line breaks.
The html function in tabulate converts tabular data into an HTML table format, making it easy to embed tables in web pages.
<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>
The latex function in tabulate formats tabular data into LaTeX-compatible tables for seamless integration into LaTeX documents.
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.
----------
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
- -------
A 23.01
B 35.234
C 42.4568
- -------
To not use this feature, use disable_numparse=True
- --------
A 23.01
B 35.234
C 42.45678
- --------
Here it reads numbers as string and does not aligns it due to numalign.
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).
You can customize the number format for all decimal columns in Tabulate using the floatfmt argument.
- -----
A 23.01
B 35.23
C 42.46
- -----
intfmt works similarly for integers
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.
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:
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
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.
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.
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.
Use Case: A sales manager wants to generate a quick summary of product sales.
Real-Life Application: Used in retail businesses for sales summaries.
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.
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.
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.
Use Case: A logistics company wants to customize the layout of their shipment report.
Real-Life Application: Used in logistics companies for structured reports.
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)
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
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.
Tabulate offers various table formats (e.g., ‘grid’, ‘pipe’, ‘orgtbl’, ‘rst’) that can be easily changed to suit different output needs.
Tabulate automatically aligns numeric columns to the right and text columns to the left, improving readability.
Tabulate allows easy control over decimal places for float values using the ‘floatfmt’ parameter.
Tabulate can create ASCII art tables that are more visually appealing and easier to read in plain text environments.
Tabulate can work with various data structures (lists, dictionaries, pandas DataFrames) making it versatile for different data sources.
Tabulate can generate tables in Markdown and other formats, which is useful for documentation and web content.
Tabulate offers better control over column widths, ensuring a more consistent look across different data types.
Tables generated by tabulate are often easier to copy and paste into other applications while maintaining their structure.
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
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.
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.
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.
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