I would like to export a dataframe containing percentage values like
df = pd.DataFrame([0.2323, 0.5254, 1], columns=['c'])
to LaTeX which can be done by
df.style.format('{:.2%}').to_latex()
This returns
\begin{tabular}{lr}
& c \\
0 & 23.23% \\
1 & 52.54% \\
2 & 100.00% \\
\end{tabular}
which is obviously no valid TeX code since %
is not properly escaped. How do I do that?
df.to_latex(float_format='{:0.2%}'.format)
would work but I get a deprecation warning:
FutureWarning: In future versions `DataFrame.to_latex` is expected to utilise the base implementation of `Styler.to_latex` for formatting and rendering. The arguments signature may therefore change. It is recommended instead to use `DataFrame.style.to_latex` which also contains additional functionality.
I found a wonderful tool that does what I need wonderfully: tabulate
df = pd.DataFrame([0.2323, 0.5254, 1], columns=['c'])
print(tabulate(df, intfmt=",", floatfmt='.2%', tablefmt='latex', headers=df.columns))
prints
\begin{tabular}{rr} \hline & c \\ \hline 0 & 23.23\% \\ 1 & 52.54\% \\ 2 & 100.00\% \\ \hline \end{tabular}
Yet another option could be texttable
(or its latex-focused extensions latextable
), but I haven't checked them yet.