How to Pretty-Print Tables in Python
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('| | | 4> | |'.format(*row))
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)
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))
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'))
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'))
col 1 | col 2 | col 3 | col 4 |
---|---|---|---|
1 | 2222 | 30 | 500 |
4 | 55 | 6777 | 1 |
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)
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)
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!
Как в Python сделать вывод таблицей?
javedimka: h2 = wifi.find_all(‘h2’) посмотрите пожалуйста внимательно html код или вы только обратили внимаение на не правильно сформулированную суть вопроса?
Дмитрий: Хтмл не смотрел, зачем? Что-то было в твоем вопросе и это что-то заставило мня написать про find_all. В любом случае не очень понятно, что требуется. Если надо просто вывести содержимое этих тегов то гугли про парсинг вложенных тегов, смотри методы в документации бс. Ну а если не получится найти и кто-то другой не ответит, то вечером, как приду домой — отвечу я, с телефона не очень.
javedimka: в краце есть кусок html в итоге надо вывести как я понимаю словарь th[0]:td[0] и так далее но чето цыкл против меня пока что тк я неопытен и только учусь питону
Самый простой способ с помощью Python вывести таблицу с данными в терминале или cmd это установить какой-нибудь модуль для ascii таблиц, например: PrettyTable
$ pip install PrettyTable
from prettytable import PrettyTable # Импортируем установленный модуль. # Определяем твою шапку и данные. th = [. ] td = [. ] columns = len(th) # Подсчитаем кол-во столбцов на будущее. table = PrettyTable(th) # Определяем таблицу. # Cкопируем список td, на случай если он будет использоваться в коде дальше. td_data = td[:] # Входим в цикл который заполняет нашу таблицу. # Цикл будет выполняться до тех пор пока у нас не кончатся данные # для заполнения строк таблицы (список td_data). while td_data: # Используя срез добавляем первые пять элементов в строку. # (columns = 5). table.add_row(td_data[:columns]) # Используя срез переопределяем td_data так, чтобы он # больше не содержал первых 5 элементов. td_data = td_data[columns:] print(table) # Печатаем таблицу
+-------------------+---------------+------+-------------+------------+ | MAC Address | IP Address | Mode | Rate (Mbps) | Signal (%) | +-------------------+---------------+------+-------------+------------+ | 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 | | 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 | | 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 | | 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 | | 11:11:11:11:11:11 | 192.168.0.103 | 11n | 65 | 100 | +-------------------+---------------+------+-------------+------------+
А теперь представь сколько бесполезных разговоров могло быть опущено и времени сэкономлено, если бы у тебя с первого раза получилось нормально вопрос сформулировать? Вот то-то и оно.