DEV Community

Cover image for Make a table on python
CoderLegion
CoderLegion

Posted on • Updated on • Originally published at kodblems.com

Make a table on python

Guido Van Rossum is the creator and responsible for the existence of Python. He was a Dutch-born computer scientist who was responsible for designing Python and thinking and defining all possible ways to evolve this popular programming language.

This first version of Python already included classes with inheritance, management of exceptions, functions and one of its fundamental characteristics: modular operation. This allowed it to be a much cleaner and more accessible language for people with little programming knowledge. A feature that remains to this day.

Until 2018, the development of this popular programming language was personally led by Van Rossum, but he decided to step down and, since 2019, five people decide how Python evolves and develops. A tip renewed each year.

When the first definitive version of Python was released, the popularity of this new programming language was such that comp.lang.python was created, a Python discussion board that further multiplied its number of users.

Being able to quickly organize our data in a more readable format, such as when data is disputed, can be extremely helpful in analyzing the data and planning next steps. Python offers the ability to easily convert certain types of tabular data to nicely formatted plain text tables, and that's with the tabular function .

Install tabular
First, install the library tabulated using pip install in the command line:

pip install tabulate
Then we import the tabular function from the tabular library into our code:

from tabulate import tabulate
Tabular data types supported by tabular
The tabular function can transform any of the following into an easy-to-read plain text table,

list of lists or other iterable of iterables
list or other iterable of dictations (keys as columns)
dictation of iterables (keys as columns)
two-dimensional NumPy array
NumPy record arrays (names as columns)
pandas.DataFrame
For example, if we have the following list of lists:

table = [['First Name', 'Last Name', 'Age'], ['John', 'Smith', 39], ['Mary', 'Jane', 25], ['Jennifer', 'Doe', 28]]

print(tabulate(table))

print(tabulate(table, headers='firstrow'))

print(tabulate(table, headers='firstrow', tablefmt='grid'))

print(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))
missing values
If we remove 'Jennifer' from the information dictionary above, our table will contain an empty field:

print(tabulate({'First Name': ['John', 'Mary'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]}, headers="keys", tablefmt='fancy_grid'))

print(tabulate({'First Name': ['John', 'Mary'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]}, headers="keys", tablefmt='fancy_grid', missingval='N/A'))
Hope it helps.

Top comments (0)