Printing Tables in Python: 4 Effective Methods Explained
Written on
Chapter 1: Introduction to Table Printing in Python
In this guide, we will discuss four different approaches to displaying tables in Python. We'll utilize a sample dataset to illustrate each method effectively.
Our Sample Data
We will work with the following dataset:
headers = ['fruit', 'price', 'country']
fruits = [
['apple', 4, 'sg'],
['orange', 5, 'sg'],
['pear', 6, 'sg'],
['pineapple', 7, 'sg'],
]
1. Manual Table Printing (Hardcoded)
For basic table printing, you can hardcode the values directly in your script:
headers = ['fruit', 'price', 'country']
fruits = [
['apple', 4, 'sg'],
['orange', 5, 'sg'],
['pear', 6, 'sg'],
['pineapple', 7, 'sg'],
]
for row in [headers] + fruits:
for col in row:
print(str(col).ljust(15), end='')print()
In this example, the .ljust(n) method is used to format the output, ensuring that each column has a consistent width of 15 characters. However, keep in mind that this approach may not accommodate longer strings without breaking the layout.
2. Dynamic Table Printing in Python
Instead of hardcoding the widths, you can create a dynamic solution that adjusts to the longest item in each column:
def table(headers, fruits):
data = [headers] + fruits
N = []
for i, _ in enumerate(headers):
col = [row[i] for row in data]
N.append(len(str(max(col, key=lambda x: len(str(x))))))
for row in data:
for i, col in enumerate(row):
print(str(col).ljust(N[i] + 2), end='')print()
table(headers, fruits)
This method calculates the maximum length of each column, ensuring that the table adapts to longer entries without disruption.
3. Table Creation Using Pandas
If you want a more efficient way to handle tables, consider using the Pandas library. Make sure to install it first via pip install pandas.
import pandas as pd
df = pd.DataFrame(fruits, columns=headers)
print(df)
Pandas streamlines the table creation process by allowing you to specify headers and data with minimal coding effort.
4. Using Tabulate for Table Formatting
Another popular library for table creation is Tabulate. Install it using pip install tabulate.
from tabulate import tabulate
table = tabulate(fruits, headers=headers)
print(table)
With Tabulate, you can easily create and format tables by simply passing your data and headers, simplifying the entire process.
Conclusion
While it may be tempting to manually create tables for practice, using libraries like Pandas and Tabulate can significantly enhance your productivity and ease of use. Personally, I prefer using Pandas for its robust features.
If You Wish To Support Me As A Creator
Please show your support by liking this content, leaving a comment, or sharing your favorite parts of this guide! Your engagement truly makes a difference.
In the video titled "Printing tables using Python," you will find a comprehensive guide on using various methods to print tables in Python.
The second video, "Print a formatted table using Python," dives deeper into formatting tables for better visualization and readability.