Explain Codes LogoExplain Codes Logo

Printing Lists as Tabular Data

python
dataframe
pandas
pretty-printing
Anton ShumikhinbyAnton Shumikhin·Sep 12, 2024
TLDR

For a rapid table formation in Python, utilize tabulate. Install it with pip install tabulate, then implement:

from tabulate import tabulate # Note #[1]: We are passing lists of data rows, not tuples of musical bands print(tabulate([["Alice", 30, "Engineer"], ["Bob", 22, "Artist"]], headers=["Name", "Age", "Profession"], tablefmt="grid"))

Observe the output:

+-------+-----+------------+ | Name | Age | Profession | +-------+-----+------------+ | Alice | 30 | Engineer | # Alice punching numbers in Excel | Bob | 22 | Artist | # Bob still figuring out shapes and colors +-------+-----+------------+

Tabulate is effective at transforming complex data into human-readable tables. It's as straightforward as SQL but without the cryptic queries.

Advanced examples for real Pythonistas

String format for the bravest

Let's utilize Python's Format Specification Mini-Language:

labels = ["first_name", "last_name", "major"] data = [["Alan", "Turing", "Computer Science"], ["Ada", "Lovelace", "Mathematics"]] row_format = "{:<15}" * (len(labels)) # Turing is not turning in his grave, he appreciates it for row in data: print(row_format.format(*row))

Allow yourself the joy of manually crafting your perfect table.

Dressed to impress: PrettyTable

PrettyTable enters the scene when you seek more control over sortable data and post-factum style changes:

from prettytable import PrettyTable x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.sortby = "Population" print(x)

Who would have guessed that data tables could compete with fashion shows?

Pandas DataFrame for data science aficionados

Any representation of tabular data would be incomplete without Pandas DataFrame:

import pandas as pd df = pd.DataFrame(data, columns=['Name', 'Age', 'Profession']) print(df)

This makes you wonder if Pandas are the national animal of Data Science.

Decorate your data with style

Pretty-printing with texttable

import texttable as tt tab = tt.Texttable() headings = ['Name','Age','Profession'] tab.header(headings) rows = [['Alice', 30, 'Engineer'], ['Bob', 22, 'Artist']] for row in rows: tab.add_row(row) tab.set_cols_align(['c', 'c', 'c']) print(tab.draw())

Just remember that programmers have a different understanding of "center".

Taming terminaltables and termtables

import terminaltables data = [['Name', 'Age', 'Profession'], ['Alice', 30, 'Engineer'], ['Bob', 22, 'Artist']] table = terminaltables.AsciiTable(data) print(table.table)

It's ASCII impressive!