Home > Backend Development > Python Tutorial > How Can I Easily Format Data into Tables in Python?

How Can I Easily Format Data into Tables in Python?

Barbara Streisand
Release: 2024-12-24 05:00:18
Original
675 people have browsed it

How Can I Easily Format Data into Tables in Python?

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]])
Copy after login

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))
Copy after login

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)
Copy after login

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())
Copy after login

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)],
                  >
Copy after login

Additional Options

  • terminaltables: Supports multi-line rows.
  • asciitable: Reads and writes various ASCII table formats.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template