Create Colorful Tables in Python with tabulate and colorama
In this tutorial, you’ll learn how to create colorful tables in Python using the tabulate and colorama libraries.
These tools allow you to add color and style to your data presentations.
- 1 Color entire tables
- 2 Combine foreground and background colors
- 3 Apply colors to specific columns
- 4 Coloring individual cells
- 5 Customize header row colors
- 6 Create color gradients based on data values
- 7 Conditional coloring
- 8 Highlight maximum or minimum values
- 9 Using thresholds to determine cell color
First, install the required libraries:
pip install tabulate colorama
Now, let’s import the necessary modules:
from tabulate import tabulate from colorama import Fore, Back, Style, init init(autoreset=True) data = [ ["Amr", 28, "Cairo", 75000], ["Fatima", 35, "Alexandria", 82000], ["Hassan", 42, "Giza", 95000], ["Nour", 31, "Luxor", 68000], ["Yara", 39, "Aswan", 88000] ] headers = ["Name", "Age", "City", "Salary"]
This code sets up the environment and sample data for our examples.
The init(autoreset=True)
ensures that color changes don’t persist beyond each print statement.
Color entire tables
To color an entire table, wrap the tabulate function with colorama color codes:
print(Fore.CYAN + tabulate(data, headers=headers, tablefmt="grid"))
This code produces a cyan-colored table with a grid format. The entire table, including headers and data will be displayed in cyan.
Combine foreground and background colors
You can combine foreground and background colors for a more striking effect:
print(Fore.WHITE + Back.BLUE + tabulate(data, headers=headers, tablefmt="fancy_grid"))
This example creates a table with white text on a blue background.
Apply colors to specific columns
To apply colors to specific columns, you can modify the data before passing it to tabulate:
colored_data = [ [Fore.GREEN + row[0] + Style.RESET_ALL, row[1], row[2], Fore.YELLOW + str(row[3]) + Style.RESET_ALL] for row in data ] print(tabulate(colored_data, headers=headers, tablefmt="simple"))
This code colors the “Name” column green and the “Salary” column yellow.
The Style.RESET_ALL
is used to reset the color after each colored entry to ensure that only the intended columns are colored.
Coloring individual cells
You can color individual cells based on specific conditions:
def color_salary(salary): if salary > 90000: return Fore.RED + str(salary) + Style.RESET_ALL elif salary > 80000: return Fore.YELLOW + str(salary) + Style.RESET_ALL else: return Fore.GREEN + str(salary) + Style.RESET_ALL colored_data = [ [row[0], row[1], row[2], color_salary(row[3])] for row in data ] print(tabulate(colored_data, headers=headers, tablefmt="simple"))
This example colors salaries red if they’re over 90,000, yellow if they’re over 80,000, and green otherwise.
Customize header row colors
To make the header row stand out, you can apply a different color:
colored_headers = [Fore.MAGENTA + Style.BRIGHT + header + Style.RESET_ALL for header in headers] print(tabulate(data, headers=colored_headers, tablefmt="grid"))
This code creates a table with bright magenta headers.
Create color gradients based on data values
You can create a color gradient for numeric values:
import numpy as np def color_gradient(value, min_val, max_val): norm_value = (value - min_val) / (max_val - min_val) r = int(255 * norm_value) g = int(255 * (1 - norm_value)) return f"\033[38;2;{r};{g};0m{value}\033[0m" ages = [row[1] for row in data] min_age, max_age = min(ages), max(ages) gradient_data = [ [row[0], color_gradient(row[1], min_age, max_age), row[2], row[3]] for row in data ] print(tabulate(gradient_data, headers=headers, tablefmt="simple"))
This code creates a color gradient for the “Age” column, with younger ages in green and older ages in red.
Conditional coloring
You can apply colors based on multiple conditions:
def color_row(row): name, age, city, salary = row if age > 35 and salary > 80000: return [Fore.CYAN + str(cell) + Style.RESET_ALL for cell in row] elif city in ["Cairo", "Alexandria"]: return [Fore.YELLOW + str(cell) + Style.RESET_ALL for cell in row] else: return [str(cell) for cell in row] colored_data = [color_row(row) for row in data] print(tabulate(colored_data, headers=headers, tablefmt="grid"))
This example colors rows cyan if the person is over 35 and earns more than 80,000, yellow if they’re from Cairo or Alexandria, and leaves other rows uncolored.
Highlight maximum or minimum values
To highlight the maximum or minimum values in a column:
salaries = [row[3] for row in data] max_salary = max(salaries) highlighted_data = [ [Fore.RED + Style.BRIGHT + str(cell) + Style.RESET_ALL if i == 3 and cell == max_salary else str(cell) for i, cell in enumerate(row)] for row in data ] print(tabulate(highlighted_data, headers=headers, tablefmt="simple"))
This code highlights the highest salary in bright red.
Using thresholds to determine cell color
You can use thresholds to apply different colors to cells:
def color_salary(salary): if salary <= 70000: return Fore.GREEN + str(salary) + Style.RESET_ALL elif 70000 < salary <= 85000: return Fore.YELLOW + str(salary) + Style.RESET_ALL else: return Fore.RED + str(salary) + Style.RESET_ALL colored_data = [ [row[0] + Style.RESET_ALL, row[1], row[2], color_salary(row[3])] for row in data ] print(tabulate(colored_data, headers=headers, tablefmt="simple"))
This example colors salaries green if they’re 70,000 or less, yellow if they’re between 70,000 and 85,000, and red if they’re above 85,000.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.