Kodeclik Blog
How to make a table in Python
Creating tables in Python is often necessary in various data-related tasks and scenarios. For instance, you might need to create tables for data analysis, to store information you scraped from a website, or in general to structure information for later purposes.
Method 1: The tabulate module
The tabulate module provides a simple and flexible way to create tables in Python. It can be installed using pip and imported into your script. To create a table, you typically prepare your data as a list of lists or a dictionary, then pass it to the tabulate function along with any desired formatting options.
Here's an example using tabulate:
from tabulate import tabulate
data = [["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "San Francisco"],
["Charlie", 35, "London"]]
print(tabulate(data, headers="firstrow", tablefmt="grid"))
This code creates a simple table with headers and a grid format:
+---------+-------+---------------+
| Name | Age | City |
+=========+=======+===============+
| Alice | 25 | New York |
+---------+-------+---------------+
| Bob | 30 | San Francisco |
+---------+-------+---------------+
| Charlie | 35 | London |
+---------+-------+---------------+
For a more sophisticated look, you can use the fancy_grid format:
print(tabulate(data, headers="firstrow", tablefmt="fancy_grid"))
This produces a table with double-line borders, giving it a more polished appearance.
╒═════════╤═══════╤═══════════════╕
│ Name │ Age │ City │
╞═════════╪═══════╪═══════════════╡
│ Alice │ 25 │ New York │
├─────────┼───────┼───────────────┤
│ Bob │ 30 │ San Francisco │
├─────────┼───────┼───────────────┤
│ Charlie │ 35 │ London │
╘═════════╧═══════╧═══════════════╛
If you need to generate HTML code for your table, tabulate makes it easy:
print(tabulate(data, headers="firstrow", tablefmt="html"))
This outputs the table as HTML, which can be useful for web applications or reports.
<table>
<thead>
<tr><th>Name </th><th style="text-align: right;"> Age</th><th>City </th></tr>
</thead>
<tbody>
<tr><td>Alice </td><td style="text-align: right;"> 25</td><td>New York </td></tr>
<tr><td>Bob </td><td style="text-align: right;"> 30</td><td>San Francisco</td></tr>
<tr><td>Charlie</td><td style="text-align: right;"> 35</td><td>London </td></tr>
</tbody>
</table>
Method 2: The prettytable module
The prettytable module offers another approach to creating tables in Python. It allows you to build tables row by row or column by column. Here's an example:
from prettytable import PrettyTable
table = PrettyTable()
table.field_names = ["Name", "Age", "City"]
table.add_row(["Alice", 25, "New York"])
table.add_row(["Bob", 30, "San Francisco"])
table.add_row(["Charlie", 35, "London"])
print(table)
This creates a nicely formatted table with borders and aligned columns.
+---------+-----+---------------+
| Name | Age | City |
+---------+-----+---------------+
| Alice | 25 | New York |
| Bob | 30 | San Francisco |
| Charlie | 35 | London |
+---------+-----+---------------+
Method 3: The pandas library
Finally, if you are working with pandas dataframes, you can easily convert your data to a table format:
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'San Francisco', 'London']}
df = pd.DataFrame(data)
print(df.to_string(index=False))
This method is particularly useful when working with larger datasets or when you need to perform data manipulation before displaying the table. The output in this case is:
Name Age City
Alice 25 New York
Bob 30 San Francisco
Charlie 35 London
In summary, creating tables in Python is a versatile skill that's applicable across many domains of data science, software development, and business intelligence. The three methods discussed above are suited for different scenarios, e.g., pandas for data analysis. Which method is your favorite?
If you liked this blogpost, checkout our blogposts on numpy.ones and how to convert a python list into a numpy array!
Want to learn Python with us? Sign up for 1:1 or small group classes.