Back to articles list Articles
8 minutes read

How to Pretty-Print Tables in Python

Do you want to make your tabular data look nice in Python? There are some useful libraries to get the job done.

In this article, we'll show you some helpful libraries to print and format a table in Python quickly, easily, and in a visually appealing way – that is, pretty printing. With little effort, your tables will be ready for an online publication, an analytics report, or a scientific paper.

Python has emerged as one of the go-to languages for data analysis. It is powerful and flexible. Its clear and easy-to-understand syntax makes it a great language to learn, even for beginners. The huge number of open-source libraries provide functionality for everything from scraping, cleaning, and manipulating data, to visualization and machine learning.

This article is aimed at more experienced programmers and data analysts. If you're a beginner, here's a great course that gets you on your feet.

Let's start by taking a look at some quick and dirty methods to print tables in Python for those times when you're in a hurry.

Not-So-Pretty Printing

During the exploratory data analysis phase, you're right to not worry too much about aesthetics. It doesn't make sense to waste your time producing nice-looking graphs and tables. Instead, you're just interested in understanding the data.

There are some quick techniques to print a table in Python. The first is string formatting with the format() method. Let's say you have some tabular data stored in a list of lists. This can be quickly printed row-for-row as shown below:

table = [[1, 2222, 30, 500], [4, 55, 6777, 1]]
for row in table:
    print('| {:1} | {:^4} | {:>4} | {:<3} |'.format(*row))
Result of the script

This method is quick to implement and easy to understand but has some drawbacks. The most obvious one is that you must know and define the width of each column, given by the integers in the print() function. You can overcome this by writing some code to find the maximum length of the numbers in each column, but this starts to add complexity to what should be a quick job.

Notice that the second, third, and fourth columns are centered, right-aligned, and left-aligned, respectively. This is controlled by the ^, >, and < characters. Beyond this, however, you have little control over how to print the table.

Another option is the pandas library, which has become the backbone of data analytics in Python. If you feel you need to up your pandas game a little, here's an article on working with data frames. It's straightforward to convert a table into a data frame and print the contents:

import pandas as pd
table = [[1, 2222, 30, 500], [4, 55, 6777, 1]]
df = pd.DataFrame(table, columns = ['a', 'b', 'c', 'd'], index=['row_1', 'row_2'])
print(df)
Result of the script

This is simpler than the first method since you don't have to define the column widths or formatting. And it provides an option to label the columns and rows for clarity.

It is possible to customize the appearance of a printed data frame, but it is cumbersome. You can use pd.set_option() to configure things like alignment and column width, but that can quickly add many lines to your program. The number of rows that can be displayed is also restricted by a default fixed number, so you have to set the display.max_rows option to df.shape[0]+1 to see all of them.

Pretty Printing

When you finish the exploratory data analysis phase, you may want to make your tables look nicer. Two libraries provide the functionality to pretty print comma-separated values (CSV) in Python: tabulate and prettytable. These don't come standard with Python, so you have to install them with a quick pip install command.

Speaking of CSV data, if you want to learn how to read and write to this data format, check out this article. We also have some material on how to read and write Excel files in Python, which is also useful to know.

tabulate

The tabulate library provides support for a few different data types including lists of lists, NumPy arrays, and pandas data frames, among others. Once installed, you just call the library and pass your data to the tabulate function as shown below:

from tabulate import tabulate
table = [[1, 2222, 30, 500], [4, 55, 6777, 1]]
print(tabulate(table))
Result of the script

This isn't yet particularly pretty, but to get from here to something more visually appealing is just a matter of defining some optional parameters. If your table has a header, you can define this with the headers keyword, and you can define the tablefmt keyword to change the appearance.

There are many options to choose from. For those moments when you happen to be feeling a little bit fancy, you can try out the following:

table = [['col 1', 'col 2', 'col 3', 'col 4'], [1, 2222, 30, 500], [4, 55, 6777, 1]]
print(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))
Result of the script

A nice feature of this library is the large number of predefined formats to help publish tables in various ways. For example, the mediawiki format provides the table markup used in Wikipedia, which is handy if you plan on writing or editing a Wikipedia page. For analytics reports or scientific publications, there are various latex formats as well as support for publishing tables in the popular project management software Jira or on GitHub. Here’s an example showing how you can use one line of Python to prepare tabular data to be published online using the html format:

>>> print(tabulate(table, headers='firstrow', tablefmt='html'))
<table>
<thead>
<tr><th style="text-align: right;">  col 1</th><th style="text-align: right;">  col 2</th><th style="text-align: right;">  col 3</th><th style="text-align: right;">  col 4</th></tr>
</thead>
<tbody>
<tr><td style="text-align: right;">      1</td><td style="text-align: right;">   2222</td><td style="text-align: right;">     30</td><td style="text-align: right;">    500</td></tr>
<tr><td style="text-align: right;">      4</td><td style="text-align: right;">     55</td><td style="text-align: right;">   6777</td><td style="text-align: right;">      1</td></tr>
</tbody>
</table>

prettytable

The prettytable library provides an alternative solution with some unique functionality. We'll use the PrettyTable() class to define, modify, and print tables in Python.

Here's how to define a table object with the header information, and then add multiple rows at once using the add_rows() method:

from prettytable import PrettyTable
table = [['col 1', 'col 2', 'col 3', 'col 4'], [1, 2222, 30, 500], [4, 55, 6777, 1]]
tab = PrettyTable(table[0])
tab.add_rows(table[1:])

From here, you can simply print() the table to visualize it in ASCII form, or you can use the many available methods to modify and format tabular data. To add a single row, there’s the add_row() method; to add a column, use the add_column() method. The latter has two required arguments: a string to define fieldname and a list or tuple as column. You can also define the horizontal and vertical alignments as shown in the following example:

tab.add_column('col 5', [-123, 43], align='r', valign='t')
print(tab)
Result of the script

In many cases, you have your tabular data saved in a CSV file or a database. The prettytable library comes with the functionality to read in data from an external source such as a CSV, as shown below:

from prettytable import from_csv
with open('data_file.csv') as table_file:
    tab = from_csv(table_file)

For databases with a Python library that conforms to the Python DB-API – an SQLite database, for example – you can define a cursor object then build a table using the from_db_cursor() function from prettytable. To do this, you only need about 4 lines of Python code.

One advantage of this library is the ability to modify tabular data. Another is the additional functionality that gives you control over what data to display from the table. Using the get_string() method with the fields argument allows you to control which columns are displayed. Similarly, the start and end arguments allow you to define the indexes of the rows you want to display. This method also contains the sortby keyword, which allows you to sort your tabular data by a particular column.

Like the tabulate library, the prettytable library also comes with pre-defined formats to help publish tables in different ways. You can publish in a Microsoft-Word-friendly style, for example, and there are formats for JSON and HTML with customization options. If you are interested in learning how to process data in different file formats including CSV and JSON, take a look at this course.

If you want more fine-grained control over displaying tabular data, you can also specify properties manually. Let's take a look at a more complex example of configuring tabular data in Python:

from prettytable import ALL, FRAME
tab = PrettyTable(table[0])
tab.add_rows(table[1:])
tab.hrules = ALL
tab.vrules = FRAME
tab.int_format = '8'
tab.padding_width = 2
tab.junction_char = '.'
tab.sortby = 'col 2'
print(tab)
Result of the script

Closing Thoughts on Pretty Printing Tabular Data in Python

We have explored various ways of displaying tabular data in Python. Whether you're looking for a quick and dirty representation to help understand your data or preparing your table for publication online or in a scientific journal, the methods discussed here provide you with the tools to get started.

But there's always more to discover than what we can cover in an article. We encourage you to experiment with the code snippets and start building a nice visualization of your tabular data in Python.

If you're looking for more material on using Python for data science, check out this course. It includes useful lessons and exercises to send you on your way toward becoming a better data scientist. Happy coding!