How to Export Python tabulate to Latex Format

In this tutorial, you’ll learn how to export Python tabulate data to LaTeX format.

You’ll explore various formatting options, handle complex table structures, and deal with special characters.

 

 

Table Format Options for LaTeX

The tabulate library offers three main LaTeX formatting options: ‘latex’, ‘latex_raw’, and ‘latex_booktabs’.

To explain these options, let’s use the following sample data:

from tabulate import tabulate
data = [
    ["Ahmed", 28, "Engineer"],
    ["Fatima", 35, "Doctor"],
    ["Mohamed", 42, "Teacher"]
]
headers = ["Name", "Age", "Profession"]
print(tabulate(data, headers=headers, tablefmt="latex"))

Output:

\begin{tabular}{lrl}
\hline
 Name    &   Age & Profession   \\
\hline
 Ahmed   &    28 & Engineer     \\
 Fatima  &    35 & Doctor       \\
 Mohamed &    42 & Teacher      \\
\hline
\end{tabular}

This output generates a basic LaTeX table with horizontal lines. The ‘latex’ format adds \hline commands for table borders.

Now, let’s try the ‘latex_raw’ format:

print(tabulate(data, headers=headers, tablefmt="latex_raw"))

Output:

\begin{tabular}{lrl}
 Name    &   Age & Profession   \\
 Ahmed   &    28 & Engineer     \\
 Fatima  &    35 & Doctor       \\
 Mohamed &    42 & Teacher      \\
\end{tabular}

The ‘latex_raw’ format produces a simpler table but doesn’t escape special characters.

This allows you to include raw LaTeX code or commands within your table cells (e.g., mathematical expressions, formatting commands) without altering them.

Lastly, let’s use the ‘latex_booktabs’ format:

print(tabulate(data, headers=headers, tablefmt="latex_booktabs"))

Output:

\begin{tabular}{lrl}
\toprule
 Name    &   Age & Profession   \\
\midrule
 Ahmed   &    28 & Engineer     \\
 Fatima  &    35 & Doctor       \\
 Mohamed &    42 & Teacher      \\
\bottomrule
\end{tabular}

The ‘latex_booktabs’ format uses the booktabs package, which produces more professional-looking tables with better spacing and line weights.

 

Customizing Latex output options

You can customize the LaTeX output by adjusting various parameters. Here’s an example:

latex_table = tabulate(data, headers=headers, tablefmt="latex_booktabs", 
                       numalign="center", stralign="center")
print(latex_table)

Output:

\begin{tabular}{lcl}
\toprule
  Name   &  Age  & Profession  \\
\midrule
 Ahmed   &  28   &  Engineer   \\
 Fatima  &  35   &   Doctor    \\
 Mohamed &  42   &  Teacher    \\
\bottomrule
\end{tabular}

In this example, you’ve centered the numeric and string alignments.

 

Multi-row and multi-column tables

To create multi-row and multi-column tables, you can use LaTeX commands within your data.

Multi-row (\multirow{}) and multi-column (\multicolumn{}) cells in LaTeX tables allows you to merge cells across rows and columns.

Here’s an example:

from tabulate import tabulate
data = [
  ["\\multirow{2}{*}{John Doe}", "Math", 85],
  ["", "Science", 90],
  ["Jane Smith", "\\multicolumn{2}{c}{N/A}"],
  ["Alice Johnson", "History", 78],
  ["\\multirow{2}{*}{Bob Lee}", "Art", 88],
  ["", "Music", 92],
]
headers = ["Name", "Subject", "Score"]
latex_table = tabulate(
  data,
  headers=headers,
  tablefmt="latex_raw"
)
print(latex_table)

Output:

\begin{tabular}{llr}
\hline
 Name                      & Subject                 &   Score \\
\hline
 \multirow{2}{*}{John Doe} & Math                    &      85 \\
                           & Science                 &      90 \\
 Jane Smith                & \multicolumn{2}{c}{N/A} &         \\
 Alice Johnson             & History                 &      78 \\
 \multirow{2}{*}{Bob Lee}  & Art                     &      88 \\
                           & Music                   &      92 \\
\hline
\end{tabular}

Multi-row Cells: We use \multirow{2}{*}{Name} to merge the “Name” cell across two rows.

The cell below it is left empty ("") to maintain the table structure.

Multi-column Cells: For “Jane Smith,” we use \multicolumn{2}{c}{N/A} to merge the “Subject” and “Score” cells into one that spans two columns, centered (c).

 

Deal with special characters in Latex

Escape special characters

The tabulate library automatically escapes LaTeX special characters when you use the "latex" table format.

However, you can special characters in LaTeX manually to perform custom escaping.

Here’s how you can do it:

def escape_latex(text):
    special_chars = ['&', '%', '$', '#', '_', '{', '}', '~', '^', '\\']
    for char in special_chars:
        text = text.replace(char, f'\\{char}')
    return text
special_data = [
    ["Nour_Ahmed", "100%", "$50"],
    ["Hana & Yara", "#1", "^2"]
]
special_headers = ["Name", "Score", "Prize"]
escaped_data = [[escape_latex(str(cell)) for cell in row] for row in special_data]
escaped_headers = [escape_latex(header) for header in special_headers]
print(tabulate(escaped_data, headers=escaped_headers, tablefmt="latex_booktabs"))

Output:

\begin{tabular}{lll}
\toprule
 Name          & Score   & Prize   \\
\midrule
 Nour\textbackslash{}\textbackslash{}\_Ahmed  & 100\textbackslash{}\textbackslash{}\%  & \textbackslash{}\textbackslash{}\$50   \\
 Hana \textbackslash{}\textbackslash{}\& Yara & \textbackslash{}\textbackslash{}\#1    & \textbackslash{}\textbackslash{}\^{}2    \\
\bottomrule
\end{tabular}

This code escapes special LaTeX characters to ensure they appear correctly in the final document.

Mathematical symbols and expressions

You can include mathematical symbols and expressions in your tables using latex_raw format:

math_data = [
    ["α", "\\frac{1}{2}", "x^2"],
    ["β", "\\sqrt{2}", "y^3"],
    ["γ", "\\int_0^1 x dx", "z^4"]
]
math_headers = ["Symbol", "Expression", "Power"]
print(tabulate(math_data, headers=math_headers, tablefmt="latex_raw"))

Output:

\begin{tabular}{lll}
\hline
 Symbol   & Expression    & Power   \\
\hline
 α        & \frac{1}{2}   & x^2     \\
 β        & \sqrt{2}      & y^3     \\
 γ        & \int_0^1 x dx & z^4     \\
\hline
\end{tabular}

 

Export to a LaTeX File

To export your table to a LaTeX file, you can use Python file handling capabilities:

headers = ["Name", "Age", "Profession"]
data = [
  ["Ahmed", 28, "Engineer"],
  ["Fatima", 35, "Doctor"],
  ["Mohamed", 42, "Teacher"]
]
def create_latex_table(headers, data):
  table_content = "\\begin{tabular}{" + "l" * len(headers) + "}\n"
  table_content += "\\toprule\n"
  table_content += " & ".join(headers) + " \\\\\n"
  table_content += "\\midrule\n"
  for row in data:
      table_content += " & ".join(str(item) for item in row) + " \\\\\n"
  table_content += "\\bottomrule\n"
  table_content += "\\end{tabular}"
  return table_content
full_table = create_latex_table(headers, data)

latex_content = f"""
\\documentclass{{article}}
\\usepackage{{booktabs}}

\\begin{{document}}

{full_table}

\\end{{document}}
"""

with open("sample_table.tex", "w", encoding="utf-8") as tex_file:
  tex_file.write(latex_content)
print("LaTeX file 'sample_table.tex' has been created.")

Output:
LaTeX file ‘sample_table.tex’ has been created.

This code creates a complete LaTeX document with your table and saves it as ‘sample_table.tex’.

You can now compile this file using your preferred LaTeX compiler to generate the final PDF output.

Leave a Reply

Your email address will not be published. Required fields are marked *