Skip to content

Table examples

Run the cells in order after installation. Code comes from the original notebook. Saved outputs are previews. Output paths are relative to the working directory. This example also requires pandas.

Preamble

from pathlib import Path

import pandas as pd
import hedgehogs as hdg

Output directory

table_root = Path.cwd() / "output" / "tables"
table_root.mkdir(parents=True, exist_ok=True)

Data

results = [("Baseline", 0.0412, 1.25), ("Candidate", 0.0184, 0.82), ("Reference", 0.0102, 0.55)]

Static table

table = hdg.Table(
    "Model comparison", columns=["Model", "RMSE", "Time (s)"],
    formatters={"RMSE": ".3f", "Time (s)": ".2f"},
)
for row in results:
    table.add_row(*row)
table.show()
Model RMSE Time (s)
Baseline 0.041 1.25
Candidate 0.018 0.82
Reference 0.010 0.55

Numeric sorting

table.sort("RMSE", key=float)
table.show()
Model RMSE Time (s)
Reference 0.010 0.55
Candidate 0.018 0.82
Baseline 0.041 1.25

DataFrame

summary = pd.DataFrame(results, columns=["Model", "RMSE", "Time (s)"])
dataframe_table = hdg.Table.from_dataframe(
    summary, title="Evaluation", columns=["Model", "RMSE"],
    formatters={"RMSE": ".4f"},
)
dataframe_table.show()
Model RMSE
Baseline 0.0412
Candidate 0.0184
Reference 0.0102

Live table

live_table = hdg.Table(
    "Iterations", columns=["Iteration", "Error"],
    mode="live", formatters={"Error": ".4f"},
)
live_table.add_row(0, 0.1)
for iteration in range(1, 6):
    live_table.update_row(0, iteration, 0.1 / (iteration + 1))
live_table.finish()
Iteration Error
5 0.0167

Export

csv_path = table.to_csv(table_root / "comparison.csv")
latex = table.to_latex(table_root / "comparison.tex", caption="Model comparison", label="tab:comparison")
print(latex)
\begin{table}
\centering
\caption{Model comparison}
\label{tab:comparison}
\begin{tabular}{lrr}
\toprule
Model & RMSE & Time (s) \\
\midrule
Reference & 0.010 & 0.55 \\
Candidate & 0.018 & 0.82 \\
Baseline & 0.041 & 1.25 \\
\bottomrule
\end{tabular}
\end{table}

Plain text

print(table.to_text())
Model comparison                
┌───────────┬───────┬──────────┐
│ Model     │  RMSE │ Time (s) │
├───────────┼───────┼──────────┤
│ Reference │ 0.010 │     0.55 │
├───────────┼───────┼──────────┤
│ Candidate │ 0.018 │     0.82 │
├───────────┼───────┼──────────┤
│ Baseline  │ 0.041 │     1.25 │
└───────────┴───────┴──────────┘