df.to_latex() 的格式

Jon*_*nas 6 python latex pandas

我想将 Pandas DataFrame 导出到 LaTeX,并使用.千位分隔符、,小数分隔符和两位小数位。例如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)
Run Code Online (Sandbox Code Playgroud)

我能实现这个目标吗?如果我将收到的代码中的 更改.为 an 。谢谢你!,ValueError: Invalid format specifier

uke*_*emi 11

从 pandas v1.3.0 开始,您可以使用对象指定小数点和千位分隔符Styler

df = df.style.format(decimal=',', thousands='.', precision=2)
Run Code Online (Sandbox Code Playgroud)
>>> df.to_latex()

\begin{tabular}{lrr}
{} & {col_1} & {col_2} \\
0 & 4.511,34 & 4.842,48 \\
\end{tabular}
Run Code Online (Sandbox Code Playgroud)


B. *_*art 1

我将使用 _ 作为千位分隔符和 . 作为小数分隔符,然后用 str.replace 替换它们。

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

给出以下乳胶:

\begin{tabular}{lll}
\toprule
{} &     col\_1 &     col\_2 \\
\midrule
0 &  4.511,34 &  4.842,48 \\
\bottomrule
\end{tabular}
Run Code Online (Sandbox Code Playgroud)