0

I am rendering a PDF with quarto and python. I want to include a line break in a column header, but the commands are not being processed when the document is compiled. I have tried:

import pandas as pd

# Create a DataFrame
data = {
    'Column 1\nLine 2': [1, 2, 3],
    'Column 2\nLine 2': [4, 5, 6]
}
df = pd.DataFrame(data)

# Convert DataFrame to LaTeX table
latex_table = df.to_latex(escape=False).replace('\\n', '\\\\')

display(Latex(df.to_latex(index=False)))

which only results in backslashes in the column header.

data = {
    'Column 1\nLine 2': [99, 2, 3],
    'Column 2\nLine 2': [4, 5, 6]
}
df = pd.DataFrame(data)

# Convert DataFrame to a tabulate table in LaTeX format
table_latex = tabulate(df, headers='keys', tablefmt='latex')

# Display the LaTeX table
display(Latex(table_latex))

Which produces a single line header with no additional notation.

---
title: "wow"
format:
    pdf:
        documentclass: article
        keep-tex: false
        include-in-header:
            text: |
                \usepackage{makecell}
--

```{python}
data = {
    '\makecell{Column 1 \\ Line 2}': [88, 2, 3],
    '\makecell{Column 1 \n Line 2}': [4, 5, 6]
}
df = pd.DataFrame(data)

# Convert DataFrame to a tabulate table in LaTeX format
table_latex = tabulate(df, headers='keys', tablefmt='latex')

# Display the LaTeX table
display(Latex(table_latex))

Where the cells read as \makecell{Column 1 \ Line 2} and \makecell{Column 2 Line 2} respectively.

I am looking for any solution that will allow the column headers to include line breaks. Quarto version 1.5.53

1 Answer 1

0

After more exploring, I found a solution.

```{python}

import pandas as pd
from tabulate import tabulate
from IPython.display import display, Latex

data = {
    'Column 1 \\\ Line 2': [1, 2, 3],
    'Column 2 Line 2': [4, 5, 6]
}
df = pd.DataFrame(data)

with open("table.tex", "w") as f:
    f.write(latex_table)

print(latex_table)
```

```{=latex}
\input{table.tex}
```

Not the answer you're looking for? Browse other questions tagged or ask your own question.