"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to format data into tables easily in Python?

How to format data into tables easily in Python?

Posted on 2025-04-18
Browse:981

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]])

The desired output is a table with the heading names as columns and the matrix values as rows:

Man UtdMan CityT Hotspur
Man Utd100
Man City110
T Hotspur012

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

  • 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.

Latest tutorial More>

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