使用 python pandas 生成具有多个列级别的 latex 表

使用 python pandas 生成具有多个列级别的 latex 表

我正在尝试使用to_latex来自 pandas 的函数创建一个乳胶表,但无法获得具有多个列级别的美观表。

在 pandas 中创建具有多个列级别的数据框时,该方法生成的表to_latex没有将较高级别的列名与较低级别的列名对齐。有人知道如何解决这个问题吗?或者也许有更好的方法用 python 生成 latex 表?

生成“坏”乳胶表的代码:

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(3, 2), columns=list('AB'), index=pd.date_range('20000101', periods=3))
df2 = pd.DataFrame(np.random.randn(3, 2), columns=list('AB'), index=pd.date_range('20000101', periods=3))
df = pd.concat(dict(df1=df1, df2=df2), axis=1)
df = df.reset_index(drop=True)
df_tex = df.to_latex(index=False, escape=False)
print(df_tex)

生成的乳胶代码:

\begin{tabular}{rrrr}
\toprule
      df1 & \multicolumn{2}{l}{df2} \\
        A &         B &         A &         B \\
\midrule
-1.403931 & -0.590029 & -1.768458 &  0.441598 \\
-0.855282 &  1.519907 &  1.104805 & -0.504378 \\
-1.360559 & -0.184407 & -0.260366 & -0.469498 \\
\bottomrule
\end{tabular}

结果表: 在此处输入图片描述

答案1

如果在表中添加索引,则表头似乎已正确添加:

df_tex = df.to_latex(index=True, escape=False)

但随后显示的索引可能不是我们想要的。如果是这种情况,一种选择是将索引设置为空字符串,然后删除索引列。

n_rows, n_cols = df.shape
df = df.set_index([[""] * n_rows])
df_tex = df.to_latex(index=True, escape=False, column_format="r" * n_cols)
df_tex = df_tex.replace("{} &", "")
print(df_tex)

这将产生下表:

\begin{tabular}{rrrr}
\toprule
 \multicolumn{2}{l}{df1} & \multicolumn{2}{l}{df2} \\
         A &         B &         A &         B \\
\midrule
  1.031842 & -1.145494 & -1.091274 &  1.512416 \\
  0.390598 & -0.316574 & -0.674270 &  1.800228 \\
 -0.174679 & -0.805350 & -0.742724 & -0.273281 \\
\bottomrule
\end{tabular}

相关内容