我正在使用 quarto 和 python 渲染 PDF。我想在列标题中包含换行符,但编译文档时不会处理命令。我试过了:
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)))
这只会导致列标题中出现反斜杠。
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))
这会产生一个没有附加符号的单行标题。
---
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))
单元格分别读作
\makecell{Column 1 \ Line 2}
和 \makecell{Column 2 Line 2}
。
我正在寻找任何允许列标题包含换行符的解决方案。四开版 1.5.53
经过更多探索,我找到了解决方案。
```{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}
```