November 5, 2024

Python PrettyTable Module

Python PrettyTable Module

The PrettyTable module in Python is used for creating and displaying tables in a formatted, easy-to-read manner. It is particularly useful for presenting tabular data in a text-based format, making it ideal for CLI (Command Line Interface) applications and console output.

1. Installation

To use the PrettyTable module, you need to install it first. You can do this using pip:

pip install prettytable
		

2. Basic Usage

Here is a basic example of how to use the PrettyTable module:

from prettytable import PrettyTable

	# Create a PrettyTable object
	table = PrettyTable()

	# Define the columns
	table.field_names = ["ID", "Name", "Age"]

	# Add rows to the table
	table.add_row([1, "Alice", 24])
	table.add_row([2, "Bob", 27])
	table.add_row([3, "Charlie", 22])

	# Print the table
	print(table)
		

This will output:

+----+---------+-----+
	| ID |  Name   | Age |
	+----+---------+-----+
	|  1 | Alice   |  24 |
	|  2 | Bob     |  27 |
	|  3 | Charlie |  22 |
	+----+---------+-----+
		

3. Advanced Features

The PrettyTable module provides several advanced features for customizing the appearance of the table:

Aligning Text

table.align["Name"] = "l"  # Left align
	table.align["Age"] = "r"   # Right align

	print(table)
		

Table Borders

table.border = True  # Default is True; set to False to remove borders

	print(table)
		

Changing Table Style

table.set_style(PrettyTable.MSWORD_FRIENDLY)  # Change table style

	print(table)
		

4. Using with DataFrames

You can also use PrettyTable to display data from a pandas DataFrame:

import pandas as pd
	from prettytable import PrettyTable

	# Create a pandas DataFrame
	df = pd.DataFrame({
		"ID": [1, 2, 3],
		"Name": ["Alice", "Bob", "Charlie"],
		"Age": [24, 27, 22]
	})

	# Convert DataFrame to PrettyTable
	table = PrettyTable()
	table.field_names = df.columns
	for row in df.itertuples(index=False):
		table.add_row(row)

	print(table)
		

5. Conclusion

The PrettyTable module is a useful tool for creating formatted tables in Python. Its ability to customize table appearance and integrate with pandas DataFrames makes it a versatile choice for displaying tabular data in a clear and organized manner.