Displaying Tabular Data in Python
Python provides several built-in and third-party libraries that make it easy to display tabular data in a variety of formats. Here are some of the most commonly used techniques:
Using the print()
Function
The simplest way to display tabular data in Python is by using the print()
function. You can create a list of lists or a 2D array and print it row by row:
data = [
["Name", "Age", "Gender"],
["John", 25, "Male"],
["Jane", 30, "Female"],
["Bob", 35, "Male"]
]
for row in data:
print(", ".join(str(x) for x in row))
This will output:
Name, Age, Gender
John, 25, Male
Jane, 30, Female
Bob, 35, Male
Using the tabulate
Library
The tabulate
library provides a more sophisticated way to display tabular data. It can format the data in various styles, such as grid, simple, and fancy grid:
from tabulate import tabulate
data = [
["Name", "Age", "Gender"],
["John", 25, "Male"],
["Jane", 30, "Female"],
["Bob", 35, "Male"]
]
print(tabulate(data, headers="firstrow", tablefmt="grid"))
This will output:
+----------+-----+----------+
| Name | Age | Gender |
+----------+-----+----------+
| John | 25 | Male |
| Jane | 30 | Female |
| Bob | 35 | Male |
+----------+-----+----------+
Using the pandas
Library
The pandas
library is a powerful data manipulation and analysis tool that provides a DataFrame
object, which can be used to represent and display tabular data. DataFrame
offers a wide range of formatting options and customization features:
import pandas as pd
data = [
["John", 25, "Male"],
["Jane", 30, "Female"],
["Bob", 35, "Male"]
]
df = pd.DataFrame(data, columns=["Name", "Age", "Gender"])
print(df)
This will output:
Name Age Gender
0 John 25 Male
1 Jane 30 Female
2 Bob 35 Male
These are just a few examples of how to display tabular data in Python. The choice of the appropriate technique will depend on the specific requirements of your project, such as the size and complexity of the data, the desired output format, and the level of customization needed.