3

I'm trying to create a latex table using the to_latex function from pandas but don't manage to get to a good looking table with multiple column levels.

When creating a dataframe in pandas with multiple column levels, the table resulting from the to_latex method does not have the higher level column names aligned with the lower ones. Does someone know how to fix this issue? Or perhaps is there a better method to generate latex tables with python?

Code to generate "bad" latex table:

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)

Resulting latex code:

\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}

Resulting table: enter image description here

1
  • I also would like to know if there's a way to customise the to_latex(). While searching for that came across this but haven't tried it yet. towardsdatascience.com/…
    – MrT77
    Nov 17, 2021 at 21:26

1 Answer 1

1

The table header seems to be added correctly if the index is added to the table:

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

But then the index is shown which may not be desired. If this is the case, one option would be to set the index to empty strings and then remove the index column.

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)

This will result in the following table:

\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}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .