Skip to content

Tutorial: latex_utils

Paul Alexander Bilokon edited this page Dec 15, 2024 · 1 revision

Using LaTeX Utilities in Python

This tutorial demonstrates how to generate LaTeX tables from pandas DataFrames using the thalesians.adiutor.latex_utils library.

Overview

The latex_utils.to_booktabs_table function helps create a LaTeX table with Booktabs styling from a pandas DataFrame.

Example Test Case

The following example demonstrates how to use to_booktabs_table to convert a DataFrame into a LaTeX table.

import pandas as pd
import thalesians.adiutor.latex_utils as latex_utils

# Define the data for the DataFrame
data = {
    "Column A": [1, 2, 3],
    "Column B": [4, 5, 6],
    "Column C": ["$x$", "$y$", "$z$"]  # Escaped for LaTeX compatibility
}

# Create the DataFrame
df = pd.DataFrame(data)

# Generate the LaTeX table
latex_code = latex_utils.to_booktabs_table(
    df, caption="Example Table", label="Example Table"
)

# Print the LaTeX code
print(latex_code)

Expected Output

The LaTeX table generated by the code above:

\begin{table}[htbp]
\centering
\caption{Example Table}
\label{Example Table}
\resizebox{\textwidth}{!}{%
\begin{tabular}{lcc}
\hline\hline
Column A & Column B & Column C \\
\hline
1 & 4 & $x$ \\
2 & 5 & $y$ \\
3 & 6 & $z$ \\
\hline\hline
\end{tabular}
}
\end{table}

Explanation

  1. Input Data:

    • A pandas DataFrame is used as the input.
    • The third column contains LaTeX-compatible strings, such as $x$, $y$, and $z$.
  2. LaTeX Table Generation:

    • The to_booktabs_table function formats the DataFrame into a LaTeX table.
    • It includes a caption, label, and uses \resizebox for adjusting the table size.
  3. Integration:

    • You can integrate the generated LaTeX code into your LaTeX documents for polished, publication-quality tables.