Stücke
Stücke

Reputation: 993

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!

Upvotes: 8

Views: 6417

Answers (4)

Scriddie
Scriddie

Reputation: 3801

Round and convert contents to string

I found it simplest to apply rounding and then convert to strings to avoid zero-padding:

import pandas as pd
df = pd.DataFrame({'a': [1.2345, 2.3456]})
df = df.round(2).astype(str)  # round and convert to string
df.to_latex('table.tex', index=False)

Upvotes: 1

iacob
iacob

Reputation: 24271

As of pandas v1.3.0, you can specify the decimal and thousands separators with the Styler object:

df = df.style.format(decimal=',', thousands='.', precision=2)
>>> df.to_latex()

\begin{tabular}{lrr}
{} & {col_1} & {col_2} \\
0 & 4.511,34 & 4.842,48 \\
\end{tabular}

Upvotes: 15

B. Bogart
B. Bogart

Reputation: 1075

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}

Upvotes: 1

Stücke
Stücke

Reputation: 993

Apparently, it works with:

import locale
import numpy as np
import pandas as pd
locale.setlocale(locale.LC_ALL, '')
pd.options.display.float_format = '{:n}'.format

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

df.to_latex('table.tex')

But I guess there is a better answer which works only for the exported df!

Upvotes: 1

Related Questions