Plug4
Plug4

Reputation: 3938

Python: Pandas to latex - Issues with the backslash

I have a dataframe df for which I want to rename the columns to:

$\beta_0$, $\beta_{t-1}$ ...

such that I get the appropriate latex input. I tried the following:

df.columns = ['$ \\beta_0 $', ' $\\beta_{t-1} $', '$ \\beta_{t-2} $', '$ \\beta_{t-3} $']

I also tried r' $ \beta_0$' for intansce ... and when I do print df.to_latex() I get:

\begin{tabular}{lllll}
\toprule
{} & \$ \textbackslashbeta\_0 \$ &  \$\textbackslashbeta\_\{t-1\} \$ & \$ \textbackslashbeta\_\{t-2\} \$ & \$ \textbackslashbeta\_\{t-3\} \$ \\
\midrule

Why do the \textbackslash keeps showing up? I thought that \\ or r would have solve this issue...

Upvotes: 10

Views: 4633

Answers (1)

joris
joris

Reputation: 139172

Note: starting with pandas 2.0, the default for escape has change to False, so there is no longer a need to set it manually.

You can use the escape=False option of to_latex:

In [9]: df = pd.DataFrame([[1,2],[3,4]], columns=['$ \\beta $', r'$ \gamma $'])

In [12]: print(df.to_latex())
\begin{tabular}{lrr}
\toprule
{} &  \$ \textbackslashbeta \$ &  \$ \textbackslashgamma \$ \\
\midrule
0 &          1 &           2 \\
1 &          3 &           4 \\
\bottomrule
\end{tabular}

In [13]: print(df.to_latex(escape=False))
\begin{tabular}{lrr}
\toprule
{} &  $ \beta $ &  $ \gamma $ \\
\midrule
0 &          1 &           2 \\
1 &          3 &           4 \\
\bottomrule
\end{tabular}

Upvotes: 19

Related Questions