Problem with `DataFrame.to_latex()` escape argument

Viewed 35

If escape argument in DataFrame.to_latex is True, then the values in columns are escaped (% -> \\%).

Can I somehow specify for which columns values should be escaped? Sometimes I don't want to escape all of them.

1 Answers

Use pandas.io.formats.style.Styler.format.

df = pd.DataFrame({"a": ["1", "%"], "b": ["2", "%"], "c": ["3", "%"]})
styler = df.style
latex = styler.format(subset=["b"], escape="latex").to_latex()
print(latex)

This produces the following LaTeX table:

\begin{tabular}{llll}
  & a &  b & c \\
0 & 1 &  2 & 3 \\
1 & % & \% & % \\
\end{tabular}

In this result only the '%' in column b is escaped.

More information and examples can be found in the docs.

Related