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.
The above is the detailed content of How Can I Easily Format Data into Tables in Python?. For more information, please follow other related articles on the PHP Chinese website!