Formatting Data for Tabular Output
In Python, representing data in tabular format can be a challenge for beginners. This article provides an overview of several easy-to-implement solutions.
The Problem
Suppose you have a list containing two headings and a matrix representing table data, such as:
teams_list = ["Man Utd", "Man City", "T Hotspur"] data = np.array([[1, 2, 1], [0, 1, 0], [2, 4, 2]])
The desired output is a table with the heading names as columns and the matrix values as rows:
Man Utd | Man City | T Hotspur | |
---|---|---|---|
Man Utd | 1 | 0 | 0 |
Man City | 1 | 1 | 0 |
T Hotspur | 0 | 1 | 2 |
Solutions
1. tabulate
Tabulate provides a simple way to format data into tables:
from tabulate import tabulate print(tabulate([['Man Utd', 1, 0, 0], ['Man City', 1, 1, 0], ['T Hotspur', 0, 1, 2]], headers=teams_list))
2. PrettyTable
PrettyTable offers more customization options:
from prettytable import PrettyTable t = PrettyTable([''] teams_list) t.add_rows([[name] list(row) for name, row in zip(teams_list, data)]) print(t)
3. texttable
Texttable provides fine-grained control over table appearance:
from texttable import Texttable t = Texttable() t.add_headers(teams_list) t.add_rows(data) print(t.draw())
4. termtables
Termtables offers additional styling options:
import termtables as tt print(tt.to_string([[''] teams_list] [[name] list(row) for name, row in zip(teams_list, data)], >
Additional Options
By utilizing these solutions, you can easily present tabular data in Python with minimal effort.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3