Dataframe.to_latex create a multilevel header in latex when the index have a name

69 Views Asked by At

I have a pandas DataFrame that I styled to generate a latex table with it.

I notice that when I don't name the index, the results is a one line header with the first column empty

Unnamed index

    styled_df = df.style \
        .format_index("\\textbf{{{}}}") \
        .format(precision=1, escape="latex") \
        .format(precision=0, subset=["Bus (V)"])
    latex_df = styled_df.to_latex()

gives me

\begin{tabular}{llrrrrrr}
 & Scénario & Bus (V) & Sym Amps & X/R Ratio & Asym Amps & I Peak & I Sym 30 \\
\textbf{SDM_P11-4-PPE-LUB-EMBR-NODE} & 4 & 600 & 3955.5 & 0.3 & 3955.5 & 5593.9 & 3856.4 \\
...
\end{tabular}

from

index Scénario Bus (V) ... I Peak I Sym 30
SDM_P11-4-PPE-LUB-EMBR-NODE 4 600.0 ... 5593.9 3856.4
... ... ... ... ... ...

Notice the empty first column, which would be the index, in the LaTeX output. And only one line for the column name.

Named index

When the I name the index

df.index = df.index.rename("Équipement")

It yields the following:

\begin{tabular}{llrrrrrr}
 & Scénario & Bus (V) & Sym Amps & X/R Ratio & Asym Amps & I Peak & I Sym 30 \\
Équipement &  &  &  &  &  &  &  \\
\textbf{SDM_P11-4-PPE-LUB-EMBR-NODE} & 4 & 600 & 3955.5 & 0.3 & 3955.5 & 5593.9 & 3856.4 \\
...
\end{tabular}

Is it normal behaviour?

Can we control the where to put the index? Or simply remove it from the output?

I was expecting to have the first column with the index name. I tried to reset the index and set it to a columns with the right name, but the first column stays empty and it add the row number in my latex table.

0

There are 0 best solutions below