Whether you work with small or large datasets in Python, formatting your output can greatly enhance the overall understanding and interpretation of your data.
This is where the Python Tabulate module comes into play. Tabulate allows you to generate professionally formatted tables from your data. In this guide, you’re going to learn about how to import and use the Tabulate module in Python.
Step 1: Install Tabulate
To begin with, we need to install Tabulate. If Tabulate isn’t available on your Python environment, you can install it using pip. Simply run the following command:
1 |
pip install tabulate |
Step 2: Import the Module Into Your Project
Once the module is installed, the next step is to import it into your Python project. You can do this using the Python import keyword as shown in the following expression:
1 |
import tabulate |
Step 3: Create Your Data
Afterward, you need to set up some data that you want to tabulate. Let’s use a simple example of a list of lists:
1 2 3 4 |
data = [["Name", "Age", "City"], ["John Doe", 28, "New York"], ["Jane Doe", 26, "San Francisco"], ["Mike Jordan", 45, "Chicago"]] |
Step 4: Use the Tabulate Module to Format Your Data
With your data ready, you can now use the tabulate() function to format it. Suppose you want to format your data into a plain table. Here’s how you can achieve this:
1 |
print(tabulate.tabulate(data, headers="firstrow", tablefmt="plain")) |
The tabulate() function accepts various parameters. The headers parameter controls the headers. Here we use “firstrow” to indicate our first row in data should serve as the headings.
Full Code
Here is the full Python code that we’ve used in this guide :
1 2 3 4 5 6 7 8 |
import tabulate data = [["Name", "Age", "City"], ["John Doe", 28, "New York"], ["Jane Doe", 26, "San Francisco"], ["Mike Jordan", 45, "Chicago"]] print(tabulate.tabulate(data, headers="firstrow", tablefmt="plain")) |
Output
Name Age City John Doe 28 New York Jane Doe 26 San Francisco Mike Jordan 45 Chicago
Conclusion
In conclusion, the Python Tabulate module is a powerful tool that allows you to present data in a more organized, tabulated manner. It offers you control over the data structure and aesthetics to suit your project’s needs. The best way to master it is by practicing and experimenting with different datasets and table formats.