Pirrtools to_rich Tutorial#
This notebook demonstrates all features of the to_rich
method for creating beautiful Rich tables from pandas DataFrames and Series.
Setup#
First, let’s import the required libraries and create sample data:
[ ]:
import pandas as pd
import pirrtools
from rich.console import Console
from rich import box
import numpy as np
# Create console for output
console = Console()
# Create sample DataFrame
df = pd.DataFrame({
'Q1': [100.123, 150.456, 200.789],
'Q2': [120.50, 180.75, 220.25],
'Q3': [140.0, 200.0, 180.0],
'Q4': [160.555, 170.333, 240.111]
}, index=['Product A', 'Product B', 'Product C'])
print("Sample DataFrame:")
df
Basic conversion#
table = df.pirr.to_rich(title=”Basic Rich Table”) console.print(table)
[ ]:
# Basic conversion using to_rich_docs for better documentation display
table = df.pirr.to_rich_docs(title="Basic Rich Table", theme="dark")
console.print(table)
Background gradient with viridis colormap#
table = df.pirr.to_rich( bg=”viridis”, title=”📊 Background Gradient (Viridis)”, column_header_style=”bold white on blue” ) console.print(table)
[ ]:
# Different colormap with axis control
table = df.pirr.to_rich(
bg="plasma",
bg_kwargs={"axis": 0}, # Column-wise gradient
title="🌈 Plasma Gradient (Column-wise)"
)
console.print(table)
Text Gradients#
Apply gradients to the text itself:
[ ]:
# Text gradient
table = df.pirr.to_rich(
tg="coolwarm",
title="🎨 Text Gradient (Coolwarm)",
index_style="bold cyan"
)
console.print(table)
String Formatting#
Format numbers and strings using the enhanced format parameter:
[ ]:
# Different formats for different columns
table = df.pirr.to_rich(
format={
'Q1': '${:.0f}', # Currency format
'Q2': '{:.1f}M', # Millions format
'Q3': '{:.0f}', # Integer format
'Q4': '{:.2f}%' # Percentage format
},
title="💰 Custom Number Formatting"
)
console.print(table)
Pandas Styler Integration#
Use existing pandas Styler objects with enhanced to_rich features:
[ ]:
# Create pandas styler with custom formatting
styler = df.style.format({
'Q1': 'Product: {:.1f}',
'Q2': 'Sales: ${:.0f}K',
'Q3': '{:.0f} units'
})
# Use styler with to_rich
table = df.pirr.to_rich(
styler=styler,
title="🏭 Pandas Styler Integration"
)
console.print(table)
Format Override#
Override styler formats with the format parameter:
[ ]:
# Original styler format
original_styler = df.style.format({'Q1': 'OLD: {:.1f}', 'Q2': 'KEEP: {:.0f}'})
# Override some formats
table = df.pirr.to_rich(
styler=original_styler,
format={'Q1': 'NEW: ${:.0f}', 'Q3': 'ADDED: {:.1f}'}, # Overrides Q1, adds Q3
title="🔄 Format Override Demo"
)
console.print(table)
Alternating Rows#
Improve readability with alternating row colors:
[ ]:
# Alternating row colors
table = df.pirr.to_rich(
alternating_rows=True,
alternating_row_colors=("", "on grey11"),
title="📋 Alternating Row Colors"
)
console.print(table)
Manual Table Control#
Override automatic table optimization for custom styling:
[ ]:
# Manual table settings
table = df.pirr.to_rich(
auto_optimize=False,
box=box.DOUBLE,
padding=(1, 2),
show_edge=True,
title="⚙️ Manual Table Control"
)
console.print(table)
Series Support#
to_rich also works with pandas Series:
[ ]:
# Create a Series
series = pd.Series([0.123, 0.456, 0.789],
name='Performance Metrics',
index=['Accuracy', 'Precision', 'Recall'])
# Format the Series
table = series.pirr.to_rich(
format='{:.1%}',
title="📈 Series with Formatting",
index_style="bold blue"
)
console.print(table)
Professional Report Style#
Combine multiple features for professional-looking reports:
[ ]:
# Professional styling combining multiple features
table = df.pirr.to_rich(
bg="viridis",
format={
'Q1': '${:.0f}K',
'Q2': '${:.0f}K',
'Q3': '${:.0f}K',
'Q4': '${:.0f}K'
},
column_header_style="bold white on dark_blue",
index_header_style="bold yellow on dark_red",
index_style="italic cyan",
alternating_rows=True,
alternating_row_colors=("", "on grey11"),
title="📊 Quarterly Sales Report - 2024"
)
console.print(table)
Large Dataset Example#
Demonstrate with a larger dataset:
[ ]:
# Create larger dataset
np.random.seed(42)
large_df = pd.DataFrame({
'Revenue': np.random.uniform(50000, 200000, 8),
'Profit': np.random.uniform(5000, 50000, 8),
'Growth': np.random.uniform(-0.1, 0.3, 8),
'Market_Share': np.random.uniform(0.05, 0.25, 8)
}, index=[f'Region_{i}' for i in range(8)])
# Display with comprehensive formatting
table = large_df.pirr.to_rich(
bg="plasma",
format={
'Revenue': '${:,.0f}',
'Profit': '${:,.0f}',
'Growth': '{:+.1%}',
'Market_Share': '{:.1%}'
},
title="🌍 Regional Performance Dashboard",
column_header_style="bold white on purple",
show_index=True
)
console.print(table)
CLI Tutorial Command#
After installing pirrtools, you can also run an interactive tutorial from the command line:
pirrtools-tutorial
This launches a comprehensive interactive tutorial covering all features.
Summary#
The to_rich
method provides powerful formatting capabilities:
✅ Background & text gradients for data visualization
✅ String formatting with pandas Styler integration
✅ Manual table control to override automatic optimization
✅ Professional styling options for reports
✅ Series support with all formatting features
✅ Easy console output with Rich integration
For more details, see the documentation and API reference.