Search code examples
pythonpandaslatex

Formatting of df.to_latex()


I want to export a Pandas DataFrame to LaTeX with . as a thousand seperator and , as a decimal seperator and two decimal digits. E.g. 4.511,34

import numpy as np
import pandas as pd

df = pd.DataFrame(
    np.array([[4511.34242, 4842.47565]]),
    columns=['col_1', 'col_2']
    )

df.to_latex('table.tex', float_format="{:0.2f}".format)

Ho can I achieve this? If I change the . to an , in the code I receive ValueError: Invalid format specifier. Thank you!


Solution

  • I would format with _ as the thousands seperator and . as the decimal seperator and then replace those with str.replace.

    df.applymap(lambda x: str.format("{:0_.2f}", x).replace('.', ',').replace('_', '.')).to_latex('table.tex')
    

    Gives the following latex:

    \begin{tabular}{lll}
    \toprule
    {} &     col\_1 &     col\_2 \\
    \midrule
    0 &  4.511,34 &  4.842,48 \\
    \bottomrule
    \end{tabular}